
Pass variable from blade to controller Laravel
Pass variable from blade to controller Laravel
We will use programming in this lesson to attempt to solve the "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.-
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; }
Output:
{"id":1,"name":"john","email":"john@example.com","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>
Output:
User ID = 1
User Name = summerThis 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.
-
Pass variable class from child view to layout
//Extending sidebar layout in child view and passing the variable name to the layout. //resources\views\article.blade.php @extends('layouts.sidebar', ['body_class' => 'article']) //Display variable name to body class in layout. //resources\views\layouts\sidebar.blade.php <body class="{{ $body_class ?? ''}}"> //Or <body class="{{ !empty($body_class) ? $body_class : '' }}">
You can pass variable class name from the child view (article.blade.php) to the sidebar layout and after that, you can display class to your body in the laravel layout file (sidebar.blade.php) which you are extending in the child view file.
-
Pass javascript variable value to laravel route on ajax call
<script> var id = $('#recordID').val(); var url = '{{ route("deleteRecord", ":id") }}'; url = url.replace(':id', id); //Call ajax $.ajax({ type : "POST", url : url, success:function(response){ console.log(response); } }); </script> <!-- Laravel route definition and generated URL --> Route::post('/delete-record/{id}', [RecordController::class, 'delete'])->name('deleteRecord'); <!-- #Generated URL --> http://localhost:8000/delete-record/1
You can pass javascript value to laravel route using replace method on url variable and assign to url parameter of ajax method.
-
Validate variable if value of variable is null, empty and has blank spaces in javascript
<script> function isNullEmptyBlank(str){ return str === null || str.match(/^ *$/) !== null; } var addr = ''; if(isNullEmptyBlank(addr)){ console.log('The value of variable is null, empty or has blank spaces'); } </script>
Output:
The value of variable is null, empty or has blank spaces
This code snippet will validate input variable if value of variable is null (null), empty ('') and has blank spaces(' ').
-
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>
Output:
User ID = 1
User Name = summerThis 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.
-
Pass variable (id) to another page as route parameter via controller in Laravel
//resources\views\welcome.blade.php @php $ID = 1; @endphp <a href="{{ route('id.detail', ['id'=>$ID]) }}"> Get id value in another view </a> //routes\web.php Route::get('get-id/{id}', [HomeController::class, 'getUserDetail'])->name('id.detail'); //app\Http\Controllers\HomeController.php public function getUserDetail($id){ return view('home')->with(['id'=> $id]); } //resources\views\home.blade.php <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <title>Home page !</title> </head> <body> <h1> {{ $id }} </h1> </body> </html>
Generated URL:
http://localhost:8000/get-id/1
Output:
1
-
Define variable and use in controller's method
Create a private variable and get the value of api key from .env file using
$_ENV['APP_API_KEY']
and pass the value to variable.app\Http\Controllers<SomeController>.php
class SomeController extends Controller{ private $apiKey; public function __construct() { $this->apiKey = $_ENV['APP_API_KEY']; } public function index() { $apikeyval = $this->apiKey; }
.env
APP_API_KEY = "5d1c88f1-bd63-428c-acce-eae8d1713445"
-
How to initialize variable in javascript to avoid errors?
Use Linter Setting that Automatically Initializes All Variables. We can use a linter to check that all variables are initialized. This makes the process automatic so that we can avoid errors.
-
Can I declare a variable without initializing JavaScript?
We can use the let keyword. We use the let keyword when variables are mutable. That means we can change or set the value later on in the program. When the value of the variable will never change, when it stays constant, we use the keyword const.
-
How to pass variable in HREF in Laravel code example?
{{ url('projects/display/'.$projects->id) }}
-
How to pass two variable in HREF in Laravel?
- Define route with multiple parameters.
- Define Controller Method With Multiple Parameters.
- Define Named Route With Multiple Parameters.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Class 'App\Http\Controllers\User' not found
- Laravel URL validation not working
- Ignore Records where a field has NULL value in Laravel
- Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request
- SQLSTATE[42000]: Syntax error or access violation: 1055
- How to check records exist in loaded relationship in Laravel blade view
- How to get data from two tables in laravel
- How to avoid duplicate entries in pivot table in Laravel
- How to check data inserted or deleted in pivot after toggle method
- How to check relationship is loaded or not in Laravel
- How to insert multiple rows in mysql using loop in laravel?
- Laravel clone model
- Retrieve count of nested relationship data in Laravel
- Split an Eloquent Collection by half in Laravel
- Laravel get count with where condition
- How to Get records between two dates in Laravel
- Symlink(): No such file or directory
- How to check query string exists or not in laravel blade
- Cannot end a section without first starting one
- Datetime field in Laravel migration
- Laravel API response format
- How to upload image in laravel 8
- How to use bootstrap pagination in laravel 8
- Class 'App\Rules\Hash' not found in Laravel
- Comment .env file in laravel