【问题标题】:Laravel 5.6 ErrorException Trying to get property 'slug' of non-objectLaravel 5.6 ErrorException 试图获取非对象的属性“slug”
【发布时间】:2018-05-20 00:22:13
【问题描述】:

我收到错误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)

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

在路由/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');

如您所见,我没有使用默认的 CRUD 资源 URL,而是定义了自己的 URL 以进入特定的 CRUD 操作。我也尝试将 $product->slug 更改为 $product->id 但结果相同,我得到了那个错误。

我在这里缺少什么?顺便说一句,我是 Laravel 的新手。

提前致谢。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果要使用route model binding,则必须将路由参数名称与方法参数匹配(或使用explicit binding

    改变这个:

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

    到这里:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 2018-11-02
      • 2018-12-09
      • 2021-07-19
      相关资源
      最近更新 更多