How can I get id from url with Request $request? (Laravel 5.3)

22,931

Solution 1

You can get it like this

$request->route('id')

Inside request class you can access it this way

$this->route('id')

I usually use it when I'm validating field to make sure it's unique, and I need to exclude model by ID when I'm doing update

Solution 2

This is because you're passing the id parameter through url, you should send it using a form like this

{!! Form::open(['route'=>' route('message.inbox.detail.id', 'method'=> 'POST']) !!}
 <input type="hidden" name="id" value="{{ $message->id }}" />
{!! Form::submit({{ trans('button.view') }}, ['class'=>'btn btn-default']) !!}
{!! Form::close() !!}

and now you can access via request in your controller

public function detail(Request $request)
{


 dd($request->input('id'));
}
Share:
22,931

Related videos on Youtube

samuel toh
Author by

samuel toh

Updated on September 17, 2021

Comments

  • samuel toh
    samuel toh over 2 years

    My link href on the view is like this :

    <a href="{{ route('message.inbox.detail.id', ['id' => $message->id]) }}" class="btn btn-default">
        <span class="fa fa-eye"></span> {{ trans('button.view') }}
    </a>
    

    My routes is like this :

    Route::get('message/inbox/detail/id/{id}', ['as'=>'message.inbox.detail.id','uses'=>'MessageController@detail']);
    

    When clicked, the url display like this :

    http://myshop.dev/message/inbox/detail/id/58cadfba607a1d2ac4000254
    

    I want get id with Request $request

    On the controller, I try like this :

    public function detail(Request $request)
    {
        dd($request->input('id'));
    }
    

    The result : null

    How can I solve it?

  • samuel toh
    samuel toh about 7 years
    Does it can not use parameters Request $request?
  • SteD
    SteD about 7 years
    for get, this is how you will have to pass it into your controller, Request $request can be used in other http method.
  • rosscooper
    rosscooper over 6 years
    This is the correct answer, worth noting it may not be id. The parameter you pass should be the same name as the parameter in the route definition.
  • totymedli
    totymedli over 2 years
    @rosscooper Exactly. If you defined the route like this: Route::apiresource('car', 'Api\CarController'), you have to use $request->route('car') or $request->route()->parameters['car']. You can get the request object with request(), $request which is coming from the controller method's parameter, or $this inside a request object.