Anik Biswas
Anik Biswas

Reputation: 135

Error while editing a post using Laravel update

This is my html form

<form class="form-horizontal" action="{{action('BlogController@update',[$blog->id]) }}" method="post">
            <input name="method" type="hidden" value="patch"/>
            <div class="form-group">
            <input name="_token" type="hidden" value="{{ csrf_token() }}"/>

Here is route:

Route::patch('blog/{id}','BlogController@update');

Controller :

public function update(Request $request,$id){
    $input = $request->all();
    $blog  =findOrFail($id);
    Blog::update($input);
    //var_dump($input);
    return back();
}

Can you please show me where is the issue?

Upvotes: 0

Views: 102

Answers (5)

Saravana Nadar
Saravana Nadar

Reputation: 1

                <form class="form-horizontal" action="{{route('blog.update',[$blog->id]) }}" method="post">
       {{csrf_field()}}
{{ method_field('PATCH') }}

Your Route Like This

Route::resource('blog', 'BlogController');

Your Controller

public function update(Request $request,$id){

$blog  =Blog::findOrFail($id);
$blog->database_fieldname1=$request->value1;
$blog->database_fieldname2=$request->value2;
$blog->database_fieldname3=$request->value3;
$blog->save();
return back();

}

Upvotes: 0

ysaurabh33
ysaurabh33

Reputation: 64

give the name whatever you wish say blog:

Route::patch('blog/{id}','BlogController@update')->name('blog');

your HTML code

<form class="form-horizontal" action="{{route('blog', $blog->id)}}" method="post">

hope this help you!!

Upvotes: 1

pedram afra
pedram afra

Reputation: 1213

you have many syntax problems!
try it this way:

form:

 <form class="form-horizontal" 
        action="{{ route('blog.update', ['id' => $blog->id]) }}" 
           method="post">
           {{ csrf_field() }}
                <input name="_method" type="hidden" value="patch"/>
                <!-- other inputs -->
      </form>

Route:

 Route::any('blog/{id}','BlogController@update')->name('blog.update');

Controller:

public function update(Request $request, $id){
    $blog = Blog::findOrFail($id);
    $blog->update([
   'key' => 'value'
]);
 // never use $request->all() because of security issues!
    return back();
}

Upvotes: 0

Imran
Imran

Reputation: 4750

In your code you have write $blog = findOrFail($id); to get blog which is not correct. You can do it using

$blog = Blog::findOrFail($id);

Now you have the blog, you need to update the blog. So, the update code should be

$blog->update($input);

To make this update method works, you need to make the fields(the fields you are updating) fillable in Blog model.

Upvotes: 3

Alexey Mezenin
Alexey Mezenin

Reputation: 163948

You're using the wrong syntax. Do something like this to make it work:

public function update(Request $request, $id)
{
    Blog::where('id', $id)->update($request->all());
    return back();
}

Upvotes: 2

Related Questions