Laravel 5.8中的编辑和更新功能

时间:2019-10-18 21:30:35

标签: php laravel laravel-5.8

我收到一条错误消息,内容为 “此集合实例上不存在属性[id]。(查看:C:\ newXampp \ htdocs \ testUser \ resources \ views \ Stock \ edit.blade.php)”

这是我的控制器

public class software 
{
    [JsonProperty("softwares")]
    public List<string> name { get; set; }
    public string version { get; set; }
    public string fixVersion { get; set; }
    public string vulnerabilities { get; set; }
}

这是我的路线

public function editStock(Stock $id)
    {
        //
        $Stock = Stock::find($id);
        return view('Stock.edit', compact('Stock', 'id'));
        // return response($stock);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Stock  $stock
     * @return \Illuminate\Http\Response
     */
    public function updateStock(Request $request, $id)
    {
        $request->validate([
            'id'=>'required',
            'stock_name'=>'required',
            'stock_qty'=>'required',
            'stock_unit'=>'required',
            'stock_price_per_kg'=>'required',
            'stock_weight_per_qty'=>'required'
        ]);

        $stock = Stock::find($id);
        $stock->stock_name =  $request->get('stock_name');
        $stock->stock_qty = $request->get('stock_qty');
        $stock->stock_unit = $request->get('stock_unit');
        $stock->stock_price_per_kg = $request->get('stock_price_per_kg');
        $stock->stock_weight_per_qty = $request->get('stock_weight_per_qty');
        $stock->save();

        return redirect('/Stock/index/')->with('success', 'Stock updated!');

    }

这是我的edit.blade.php

//Route for Stock
Route::get('/Stock/createStock/', 'ChicController@createStock')->name('createStock');
Route::post('/Stock/createStock/', 'ChicController@storeStock')->name('storeStock');
Route::get('/Stock/index/', 'ChicController@indexStock')->name('indexStock');
Route::get('/Stock/edit/{id}', 'ChicController@editStock')->name('editStock');
Route::post('/Stock/edit/{id}', 'ChicController@updateStock')->name('updateStock');
Route::delete('/Stock/index/{id}', 'ChicController@destroyStock')->name('deleteStock');

我已经尝试了一切,但无法解决问题。当我尝试在编辑控制器中回显$ id时,它将显示正确的$ id。因此,我不知道如何解决这个问题,也不知道为什么会这样。

1 个答案:

答案 0 :(得分:1)

对于您的editStock方法,由于正在进行隐式路由模型绑定,因此您已经从route参数接收到与Stock匹配的id模型的实例。当您将变量$id传递给Stock::find($id)时,您将传递一个模型Arrayable。这会导致find变成findMany,以为您正在传递许多ID。由于以下原因,您最终获得了一个收藏夹:

public function editStock(Stock $id)
{
    $Stock = Stock::find($id);
    return view('Stock.edit', compact('Stock', 'id'));
}

$Stock是一个集合,因为将许多传递给了find。我将其调整为仅将$id变量传递给您想要的Stock的视图。

public function editStock(Stock $id)
{
    return view('Stock.edit', [
        'Stock' => $id,
    ]);
}

您的视图现在将具有一个Stock变量,它是您想要的Stock

Laravel 5.8 Docs - Routing - Route Model Bindings - Implicit Bindings