在Laravel中更新数据

时间:2018-01-21 16:17:27

标签: laravel

这是我的代码:

路线:

Route::get('/editposts/{id}', function ($id) {
    $showpost = Posts::where('id', $id)->get();
    return view('editposts', compact('showpost'));
});


Route::post('/editposts', array('uses'=>'PostController@Update'));

控制器:

public function Update($id)
{

    $Posts = Posts::find($id);
    $Posts->Title = 10;
    $Posts->Content = 10;
    $Posts->save();

    //return Redirect()->back(); Input::get('Title')

}

和查看:

            @foreach($showpost as $showpost)

            <h1>Edit Posts :</h1>

            {{ Form::open(array('url'=>'editposts', 'method'=>'post')) }}
            Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ Form::submit('Update') }}
            {{ Form::close() }}

            @endforeach

但是当我想更新我的数据时,我收到一个错误:

http://localhost:8000/editposts/1

App \ Http \ Controllers \ PostController :: Update()

缺少参数1

4 个答案:

答案 0 :(得分:2)

您需要更改路线:

Route::post('editposts/{id}', 'PostController@Update');

然后表格:

{{ Form::open(['url' => 'editposts/' . $showpost->id, 'method'=>'post']) }}

答案 1 :(得分:0)

更正路线,指定参数

    Route::post('editposts/{id}', 'PostController@Update');

将post'id作为参数传递

  {{ Form::open(array('url'=>'editposts/'.$post->id, 'method'=>'post')) }}

        Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ 

        Form::submit('Update') }}
   {{ Form::close() }}

注意 $ post-&gt; id

答案 2 :(得分:0)

将您的发布路线更改为:

Route::post('/editposts/{id}', 'PostController@Update');

完成!

答案 3 :(得分:0)

首先声明您的路线:

Route::post('/editposts/{id}', array('uses'=>'PostController@Update'));

然后更新您的表单网址:

{{ Form::open(['url' => url()->action('PostController@Update', [ "id" => $showpost->id ]), 'method'=>'post']) }}

这假设您的模型的ID列为id

(可选)您还可以使用隐式模型绑定:

public function Update(Posts $id) {
    //No need to find it Laravel will do that 
    $id->Title = 10;
    $id->Content = 10;
    $id->save();
 }