Reputation: 15
I am new to Laravel and web programming things. I saw lecturer in tutorial, he passes an id
to a controller by using controller parameter
Route::get('/post/{id}', ['as'=>'home.post', 'uses'=>'AdminPostsController@post']);
, what is the difference comparing with passing an id
through $request
parameter from controller?
could you tell me when to use either controller parameter and request.
Upvotes: 0
Views: 6589
Reputation: 5105
One way to explain it is to refer to the HTTP verb GET you are refering to.
For a GET request to return a post where the id is 1 you will have two options:
/post/{id}
Using this method (a restful convention) you will need to pass the variable as a parameter to your controller action to access it.
public function view($id)
{
$post = Post::find($id);
...
}
/post?id=1
Using this method you pass the id as a query string parameter inside the url. Then inside a controller you access the value from the request.
public function view(Request $request)
{
$post = Post::find($request->input('id'));
...
}
Now lets say you want to create a new Post
that would typically be an HTTP verb POST request to a /post
endpoint where you access the payload of the form using the Request
.
public function create(Request $request)
{
$post = Post::create($request->only('description'));
}
Now lets say you want to update a current Post
that would typically be an HTTP verb PUT request to a /post/{id}
endpoint where you will fetch the model via the parameter and then update the data using the request.
public funciton update(Request $request, $id)
{
$post = Post::find($id);
$post->update($request->only('description'));
}
So at times you will use a combination of controller parameters with the request as well. But generally the controller parameter is for single items inside the routes that you need to access.
Upvotes: 1
Reputation: 711
Assuming you are the newbie in Web development, especially in Laravel, I suggest you read Laravel documentation. posts/{id}
retrieve the post model value that corresponds to that ID.
Route::get('/post/1', 'AdminPostsController@post']); -> returns post that has an ID 1.
When send you request like this posts/1
it will inject your model and returns corresponding id value
Or you can handle manually through controller with corresponding id.
public function posts(Request $request)
{
returns Posts::find($request->id);
}
Upvotes: 0