How to pass data to route in laravel?

You can pass data to route in laravel using different ways. First, you have to define a web route with parameters and after that, you can pass data to the web route by calling the route method to anchor tag and HTML form attribute.

Answers 3
  • Pass data to route in laravel using anchor tag

    //Passing value to id parameter
    <a href="{{ route('profile', ['id' => 1]) }}"> User profile </a>
    //routes\web.php
    //Route definition
    Route::get('/user/{id}/profile', function ($id) {
        echo 'user Id = '.  $id;
    })->name('profile');
    
    1
  • Passing data to route using form attribute in view file

    //resources\views\<user>\<update>.blade.php
    //Here we pass a static value to the $id variable. You can Get dynamic value from table 
    @php $id = 2 @endphp
    <form method="POST" action="{{ route('user.update', ['id'=>$id]) }}">
        @csrf
        <button type="submit">Submit</button>
    </form>
    
    //routes\web.php
    //Route definition to update user record with specific id
    Route::post('user/{id}/update', 'UserC[email protected]')->name('user.update');
    
    //app\Http\Controllers\UserController.php
    //Get passed route parameter value in controller
    public function update(Request $request, $id){
    	echo 'user id ='. $id;
    }
    
    1
  • Pass dynamic data (auth user id) to route in laravel

    //resources\views\<home>.blade.php
    <a href="{{ route('profile', ['id' => auth()->user()->id]) }}"> User profile </a>
    
    //routes\web.php
    Route::get('/user/{id}/profile', function ($id) {
        echo 'user Id = '.  $id;
    })->name('profile');
    
    1

    This code snippet will help you to pass the logged in user id which is dynamic value as route parameter.

  • Back to code snippet queries related laravel