I am creating an edit page for my posts. I would prefer to create an html form instead of using FORM:: so I can really learn. I am having an issue when I try to submit the data to the right controller method.
The tutorial I am using says to use
{!! Form::open(['action' => ['PostsController@update', $post->id], 'method' => 'POST'])!!}
Using my limited knowledge I tried to recreate this as
<form action="{!! Route::post('/posts', ['PostsController@update', $post->id]) !!}" method="POST">
underneath both I am using <input name="_method" type="hidden" value="PUT">
The error I get is `"
Object of class Illuminate\Routing\Route could not be converted to string (View: /Users/Chris/code/chris/resources/views/posts/edit.blade.php)
My web.php file has Route::resource('posts', 'PostsController');
which as worked for everything else until now. In my contoller, my update method has
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
// Create Post
$post = Post::find($id);
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/')->with('success', 'Post Updated');
}
What would the correct action be to submit an update for my info?
Thanks so much in advance!
replace the form action with the following: there are many solutions:
1- by using action method :
<form action=" {!! action('PostsController@update',$post->id) !!}" method="POST">
2- by naming the route
<form action=" {!! route('route-name',$post->id) !!}" method="POST">
3- by using url method
<form action=" {!! url('/posts',$post->id) !!}" method="POST">
As Lagbox pointed out in the comments:
Route::post('/posts', ['PostsController@update', $post->id])
Is for defining the route in your routes file. To get the url you can do one of the following:
Hard code the uri
action="/posts/{{ $post->id }}"
Use the url()
helper
action="{{ url("posts/$post->id") }}"
or action="{{ url("post", $post->id) }}"
Use the route()
helper (This will only work if you have given the route a name)
action="{{ route('the-route-name', $post->id) }}"
Use the action helper
action="{{ action('PostsController@update', $post->id) }}"
Here is a link to the various url helpers. My main advice here would be to mainly stick to just using one of them for a project.
Furthermore, your code should work absolutely fine the way it is for now but usually with REST (or the way Laravel uses rest) you would make either a PUT
or PATCH
request for updating instead of a POST
request. However, standard html forms only support GET
and POST
so Laravel provides a way for you to spoof the form method:
<input type="hidden" name="_method" value="PUT" />
Thank you so much Lagbox. I used
<form action=" {!! route('route-name',$post->id) !!}" method="POST">
and it worked perfectly!