Pass variable from blade to controller Laravel

You can pass variable as arguments to controller's method from blade view file. You have to create the method in controller class as a static method and you can directly call the controller's method by specifying the full path of controller in view file. You can also pass data from view to controller using anchor tag with route method and get in controller's method.

Answers 2
  • Get user details by calling controller's method from view in Laravel

    //resources\views\home.blade.php
    @php echo App\Http\Controllers\HomeController::getUserByID(1);  @endphp
    
    //app\Http\Controllers\HomeController.php
    //Create controller (HomeController) if not already created using php artisan make:controller HomeController and use below function in it.
    public static function getUserByID($id){
        $user = User::findOrFail($id);
        return $user;
    }
    
    0

    Output:

    {"id":1,"name":"john","email":"[email protected]","email_verified_at":"2021-08-02T00:38:40.000000Z",
    "created_at":"2021-08-02T00:38:40.000000Z","updated_at":"2021-08-02T00:38:40.000000Z"}

    This code snippet helps you to call the controller's method from view file. You have to create a web route, a function with static method in controller and you can call this method from view file by specifying the full path of controller class by passing argument to controller's method.

  • Passing variable data from view to controller using anchor tag in Laravel

    //routes\web.php
    use App\Http\Controllers\HomeController;
    Route::get('user/{id}/{name}', [HomeController::class, 'getUserDetail'])->name('user.detail');
    
    //app\Http\Controllers\HomeController.php
    <p>Create controller (HomeController) if not already created using <strong>php artisan make:controller HomeController </strong>and use below function in it.</p>
    public function getUserDetail($id, $name){
        echo 'User ID = '. $id. "<br />";
        echo 'User Name = '. $name;
    }
    
    //resources\views\home.blade.php
    @php $userID = 1; $name = 'summer'; @endphp
    <a href="{{ route('user.detail', ['id'=>$userID, 'name'=>$name]) }}"> Get user Deatails </a>
    
    0

    Output:

    User ID = 1
    User Name = summer

    This code snippet helps you pass the variable data using route method in anchor tag and we can get it in controller's method as parameters value. Here we have use static data and pass data to route as arguments and get the variable data in controller file. You can also pass dynamic value to route method in anchor tag in laravel.

  • Back to code snippet queries related laravel