In this laravel tutorial we are going to discuss about Views, how to create laravel views, how to call, pass data to views etc.
Views in Laravel 8:
Basically, views belong to the MVC structure, which is used to show HTML content on the web browser. It contains all HTML code along with include CSS and js file path.
In laravel 8 we can call views from two way, one from laravel controller and from routing file also.
The location of laravel 8 views files is inside resources folder.
[laravel_folder]/resourse/views/
Example to call views in Laravel 8 via Routing Method
Step 1: For example we create a users.blade.php file in the resourse/views folder. blade is template engine which is provided by laravel for fast rendering.
1 2 3 4 5 |
<html> <body> <h1>Users Page</h1> </body> </html> |
Step 2: Now call this view via laravel routing method, inside web.php route file.
We can call users.blade.php view via two routing method.
First one is via get method:
1 2 3 |
Route::get('user', function () { return view('users'); }); |
Second way to call via view method directly:
1 |
Route::view('user', 'users'); |
Output:
Example to call view in Laravel 8 from Controller Method
Step 1: Create a controller ‘UserController.php’ and write a show() function to call users view.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function show() { return view('users'); } } |
Step 2: Now write route method to call this controller method:
1 |
Route::get("user", [UserController::class, 'show']); |
This will show same output as above shown.
Note: Must add ‘UserController’ namespace in web.php route file before call controller method, otherwise it will gives you an error.
use App\Http\Controllers\UserController;
Pass URL Parameter to View: Example
To send URL parameter to view file, we need to use below code in ‘UserController.php’ controller file.
1 2 3 4 |
public function show($param) { return view("users", ["name"=>$param]); } |
And add below route method to call view with parameter value.
1 |
Route::get("user/{param}", [UserController::class, 'show']); |
To see this parameter value in web browser, need to echo parameter in users.blade.php file.
1 2 3 4 5 |
<html> <body> <h1>Hello {{$name}}</h1> </body> </html> |
Now call this view like this http://localhost:8000/user/peter. It will display parameter value on web page.