Laravel 5.6 ErrorException试图获取非对象的属性"slug" [英] Laravel 5.6 ErrorException Trying to get property 'slug' of non-object

查看:70
本文介绍了Laravel 5.6 ErrorException试图获取非对象的属性"slug"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误Trying to get property 'slug' of non-object (View: C:\laragon\www\mides\resources\views\products\edit.blade.php)

模型中,

class Product extends Model
{
    // protected $primaryKey = 'slug';

    // public $incrementing = false;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'slug', 'description', 'image', 'user_id',
    ];

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

控制器中,

 public function edit(Product $product)
    {
        $product = Product::where('slug', '=', $product)->first();

        return view('products.edit')->with('product', $product);
    }

public function show(Product $product)
    {
        $product = Product::where('slug', '=', $product)->first();

        return view('products.show')->with('product', $product);
    }

在视图中,(edit.blade.php)

In the view, (edit.blade.php)

<form role="form" method="POST" action="{{ route('products.update', $product->slug) }}">

在routes/web.php中,

In routes/web.php,

Route::prefix('/account')->group(function () {
    Route::get('/products', 'AccountController@products');
    Route::get('/add-product', 'ProductController@create');
    Route::get('/edit-product-{slug}', 'ProductController@edit');
    Route::put('/update-{slug}', 'ProductController@update');
});

Route::resource('products', 'ProductController');

如您所见,我定义了自己的URL来使用特定的CRUD操作,而不是使用默认的CRUD资源URL.我也尝试将$ product-> slug更改为$ product-> id,但是结果是一样的,我得到了那个错误.

As you can see, instead of using default CRUD resource URL, I define my own URL to go into the specific CRUD action. I'm also tried to change the $product->slug to $product->id but the results is same, I got that error.

我在这里想念的是什么?顺便说一句,我是Laravel的新手.

What I'm missing here? Btw, I'm new to Laravel.

谢谢.

推荐答案

如果要使用显式绑定)

If you want to use route model binding, you have to match the route parameter name to the method argument (or use explicit binding)

更改此:

Route::get('/edit-product-{slug}', 'ProductController@edit');

对此:

Route::get('/edit-product-{product}', 'ProductController@edit');

然后将找到的产品传递给控制器​​方法,因此无需查询它:

And then the found product will be passed to the controller method, so no need to query it:

public function edit(Product $product)
{
    return view('products.edit')->with('product', $product);
}

这篇关于Laravel 5.6 ErrorException试图获取非对象的属性"slug"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆