Laravel Views and Blade Templates

Published January 29, 2022

A Laravel Blade is a simple yet very powerful templating engine. Laravel Blade, unlike some other PHP templating engines, does not limit developers to just using PHP code in their templates. HTML and JavaScript are additional options. All of the Blade templates are compiled into pure PHP code and cached until they are changed. This means that Blade has no overhead in a Laravel application.

The Blade template files are easily identifiable among the Laravel application files because they are saved with the a.blade.php file extension, and, secondly, they are kept in the resources/views directory. The image below depicts the default Laravel Blade templates in a Laravel 8 application

 

Laravel Create views

 

Is there a relationship between controllers and routes in Laravel and blades?

The global view helper is used to return the Blade views from controllers or routes in Laravel 8 applications. The view helper's second argument is used to pass the data to the blade view.

 

Example

Route::get('/', function () {

    return view('home', ['name' => 'Clain']);

});

 

 

How to create a Laravel Blade Layout file

Creating a Blade template layout is pretty easy. Just follow the following simple steps:

 

Step 1: First of all, create a new layout folder inside the resources/views directory.  As we’ve discussed, all the blade view files are stored in the resources/views directory.

 

Step 2: Now, create a new file name it new.blade.php, and paste a sample HTML code inside.  We've also said that all the view blade files are saved with the “.blade.php”  extension

 

Laravel Create views with blade

 

Now in the next step, we will proceed to open our view on the web browser.

 

Step 3: Open your web browser and  display our view

 

Step 4: Now, we need to create a route to display our View.  To do this, open your routes/web.php and  add the following code

Route::get('/test', function() {

   return view('test');

});

 

Laravel blade example

 

Step 5: Now we can display our View differently, using the link http://localhost:8000/new

 

Laravel blade example

Conclusion

It's done. We've learned about blades and built a new Laravel View. Your needs may be met by inserting your own code into it

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

114 Views