E
E
Eugene2018-08-18 18:38:22
Laravel
Eugene, 2018-08-18 18:38:22

Why is an empty object passed after changing the route address?

Good afternoon.
There is a route Route::resource('/news', 'NewsController');in which the usual functions for creating, editing, etc. news. But in the process it was necessary to change the address to "/blog". The index method works as before, but an empty object is passed to the show method.
C /news works fine. I can't figure out what the problem is.
News Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class News extends Model
{
    protected $fillable = [
        'title',
        'body',
        'published_at',
        'news_wall',
        'slug'
    ];
    protected $dates = ['published_at'];

    //protected $dateFormat = 'Y-m-d\TH:i:s';


    /**
     * Переопределение метода для генерации slug url
     *
     * @return string
     */
    public function getRouteKeyName() {
        return 'slug';
    }
    /**
     * Статья пренадлежит пользователю
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user() {
        return $this->belongsTo('App/User');
    }
    /**
     * Выборка опубликованных статей
     *
     * @param $query
     */
    public function scopePublished($query) {
        $query->where('published_at', '<=', Carbon::now());
    }

    /**
     * Выборка статей в очередь на публикацию
     *
     * @param $query
     */
    public function scopeUnPublished($query){
        $query->where('published_at', '>', Carbon::now());
    }
    /**
     * Даёт аттрибут времени для статьи
     *
     * @param $date
     */
    public function setPublishedAtAttribute($date) {
        if($date === null) {
            $currentDate =  date('Y-m-d\TH:i:s');
            $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $currentDate);
        }else {
            $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $date)->format('Y-m-d\TH:i:s');
        }

    }
    /**
     * Красивое отображение даты и времени
     *
     * @return mixed
     */
    public function  getBeautifulDateAttribute() {
        Carbon::setLocale(config('app.locale'));
        if($this->published_at > Carbon::now()->subMonth()) {
            return $this->published_at->diffForHumans();
        }
        return $this->published_at->toDateTimeString('Y-m-d');
    }

}

NewsController
<?php

namespace App\Http\Controllers;

use App\News;
use Illuminate\Http\Request;
use App\Http\Requests\NewsRequest;
use Illuminate\Contracts\Filesystem\Factory;

use Auth;
use Image;

class NewsController extends Controller
{

    public function __construct(Factory $factory)
    {
        $this->factory = $factory;
    }
    /**
     * Отображение статей
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index() {
        $news = News::latest()
            ->published()
            ->paginate(10);

        return view('news.index', compact('news'));
    }
    /**
     * Отображение отдельной статьи
     *
     * @param News $news
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(News $news) {
        return view('news.show', compact('news'));
    }
    /**
     * Отображение формы создания статей
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create() {
        return view('news.create');
    }
    /**
     * Создает статью
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(NewsRequest $request) {
        $input = $this->imageArticleRequest($request);
        Auth::user()->news()->create($input);

        return redirect('news');
    }
    /**
     * Отображение формы редактирования запмси
     *
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id){
        $news = News::findOrFail($id);
        return view('news.edit', compact('news'));
    }
    /**
     * Обновляет статью и удаляет старое изображение
     *
     * @param $id
     * @param NewsRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update($id, NewsRequest $request) {
        $news = News::findOrFail($id);
        $input = $this->imageArticleRequest($request);;
        if($input !== null) {
            $old_image = $news->news_wall;
            $disk = $this->factory->disk('images');
            $disk->delete('/newsImages/' . $old_image);
            $news->update($input);
        }else {
            $news->update($request->all());
        }

        return redirect('news/'.$news->slug);
    }
    /**
     * Удаление записи
     * @param $id - id записи
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroy($id) {
        $news = News::findOrFail($id);
        $oldImage = $news->news_wall;
        $disk = $this->factory->disk('images');
        $disk->delete('/newsImages/' . $oldImage);
        $news->delete();

        return redirect('news');
    }
    /**
     * Функция обрезки и загрузки изображения для статьи, генерации слага
     *
     * @param $request
     * @return array
     */
    protected function imageArticleRequest($request) {
        if ($request->hasFile('news_wall')) {
            $image = $request->file('news_wall');
            $imageName = time() . "." . $image->getClientOriginalExtension();
            $savePath = public_path('images/uploads/newsImages/' . $imageName);
            Image::make($image)
                ->save($savePath);
            $input = $request->all();
            $input = array_except($input, 'pathName');
            $input['news_wall'] = $imageName;
            $title = $input['title'];
            $input['slug'] = str_slug($title);
            return $input;
        }
    }


}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Talalaev, 2018-08-21
@Eugene70

It's simple, resource controllers create routes from the forward automatically based on the base name of the route, so you now have:
Route::resource('/blog', 'NewsController');and so your resource controller expects one variable and receives another. In general, you should have written Route::resource('blogs', 'NewsController');and thus the blog variable with the object will go into the parameters. But since you have already written the $news method (yes, not successfully, how about a single number, heh. However, I myself came across such a thing).
So, in short in web :

Route::resource('blog', 'NewsController')->parameters([
    'blog' => 'news'
]);

Well, in the parameters of the controller methods, replace "$id" with "News $news" everywhere, although in general you no longer have a resource controller, for example, the store method . So maybe you'd better paint everything by hand. In general, initially resource controllers are suitable either for api logic of work, when you are dealing with a Model / Entity as a resource and you need standard methods, or many use it in their CRUD logics, but again only if the logic is without additional complications and interweavings like you. De facto, you do not have a resource controller, and I strongly recommend that you write it manually.
PS Also, for debugging routes, the command is great php artisan route:list, all the routes that Laravel generates will be visible, with the corresponding variable parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question