Search code examples
laravelrequestlaravel-controller

Laravel passing data to controller using controller parameter vs request


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.


Solution

  • 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:

    1. /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);
        ...
    }
    
    1. /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.