Laravel - Views
Laravel - Views and Blade Templates
Section titled “Laravel - Views and Blade Templates”Understanding Views
Section titled “Understanding Views”In the Model-View-Controller (MVC) architectural pattern, the “View” is responsible for presenting data to the user. In Laravel, views separate your application’s display logic from your business logic. Views are typically HTML files with embedded code (using Blade, Laravel’s templating engine) that are stored in the resources/views directory. A subdirectory within resources/views can be used to organize views further (e.g., resources/views/posts/index.blade.php).
Basic View Example
Section titled “Basic View Example”Step 1: Create a simple view file. Save the following content at resources/views/greeting.blade.php (note the .blade.php extension, which enables Blade templating):
<html> <body> <h1>Hello, World from Blade!</h1> </body></html>Step 2: Create a route in your routes/web.php file to display this view:
routes/web.php
use Illuminate\Support\Facades\Route;
Route::get('/greet', function () { return view('greeting'); // 'greeting' refers to greeting.blade.php});Step 3: Start your Laravel development server (php artisan serve) and visit the following URL in your browser:
Step 4: You should see the text “Hello, World from Blade!” displayed in an H1 tag.
Passing Data to Views
Section titled “Passing Data to Views”Often, you’ll need to pass data from your controller or route logic to your views. You can do this by passing an array of data as the second argument to the view helper function. The keys of the array become variables available within your view.
Example: Passing a Name to a View
Section titled “Example: Passing a Name to a View”Step 1: Modify or create a view file at resources/views/user/profile.blade.php:
<html> <body> <h1>Hello, {{ $userName }}!</h1> <p>Welcome to your profile page.</p> </body></html>Note the use of Blade’s echo syntax {{ $userName }}. This will display the value of the $userName variable and also automatically escape it to prevent XSS attacks.
Step 2: Add a route in routes/web.php to pass data to this view:
routes/web.php
Route::get('/profile/{name}', function ($name) { return view('user.profile', ['userName' => $name]); // Alternatively, using the with() method: // return view('user.profile')->with('userName', $name);});Step 3: Visit a URL like http://localhost:8000/profile/Alice in your browser.
Step 4: The output will be: “Hello, Alice!” followed by the welcome message. The value passed for userName (Alice in this case) is dynamically inserted into the view.
Sharing Data with all Views
Section titled “Sharing Data with all Views”Sometimes, you might need to make a piece of data available to all views rendered by your application. Laravel provides the View::share() method for this purpose. A common place to call this method is within the boot method of a service provider, such as App\Providers\AppServiceProvider.php.
Example: Sharing an Application Name
Section titled “Example: Sharing an Application Name”Step 1: Open app/Providers/AppServiceProvider.php. If it doesn’t exist, you can create it. Import the View facade and use View::share() in the boot method:
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider{ /** * Register any application services. * * @return void */ public function register() { // }
/** * Bootstrap any application services. * * @return void */ public function boot() { View::share('appName', 'My Awesome Laravel App'); }}Step 2: Now, the $appName variable will be available in all your Blade views. For instance, you could use it in resources/views/greeting.blade.php:
<html> <body> <h1>Welcome to {{ $appName }}!</h1> <p>Hello, World from Blade!</p> </body></html>Step 3: If you visit http://localhost:8000/greet, the output will now show “Welcome to My Awesome Laravel App!” demonstrating that the shared data is accessible.
Blade Templating Engine
Section titled “Blade Templating Engine”Blade is Laravel’s simple, yet powerful templating engine. Unlike other PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds no overhead to your application. Blade files use the .blade.php file extension.
Key Blade Features:
- Template Inheritance: Define a master layout and extend it in child views using directives like
@extends,@section, and@yield. - Control Structures: Blade provides convenient shortcuts for common PHP control structures, such as
@if,@foreach,@for,@while, etc. - Displaying Data: Use
{{ $variable }}to display data (escaped by default). Use{!! $variable !!}to display raw, unescaped data (use with caution). - Components & Slots: A powerful way to build reusable UI elements.
- Directives: Blade allows you to write custom directives using
@directive.
Blade Layout Example: Template Inheritance
Section titled “Blade Layout Example: Template Inheritance”Step 1: Create a master layout file at resources/views/layouts/app.blade.php:
<html><head> <title>@yield('title', 'My Application')</title> <link rel="stylesheet" href="{{ asset('css/app.css') }}"> <!-- Example asset linking --></head><body> <header> <h1>@yield('header_title', 'Welcome')</h1> </header>
@section('sidebar') <div class="sidebar"> <p>This is the master sidebar.</p> </div> @show
<div class="container"> @yield('content') </div>
<footer> <p>© {{ date('Y') }} My Application</p> </footer> <script src="{{ asset('js/app.js') }}"></script> <!-- Example asset linking --></body></html>Explanation of directives used:
@yield('sectionName', 'defaultValue'): Displays the content of a given section, or a default value if the section is not defined.@section('sectionName') ... @endsection: Defines a section of content.@show: Defines a section and immediately yields it. Useful for sidebars that child views might append to.
Step 2: Create a child page that extends this master layout. Save it at resources/views/pages/home.blade.php:
@extends('layouts.app')
@section('title', 'Homepage - My App')@section('header_title', 'Home Sweet Home')
@section('sidebar') @parent <!-- This will include the content from the parent's sidebar section --> <p>This is appended to the master sidebar from the homepage.</p>@endsection
@section('content') <h2>{{ $pageHeading }}</h2> <p>This is the main content for the homepage. Welcome, {{ $userName ?? 'Guest' }}!</p>@endsectionExplanation of directives used in child view:
@extends('layouts.app'): Specifies that this view extends thelayouts.appmaster layout.@section('title', 'Page Title'): Defines the content for the ‘title’ section defined by@yieldin the master layout.@parent: When within a section,@parentappends (or prepends) content to the parent layout’s section content.- The
??operator is the null coalescing operator, providing a default value if$userNameis not set.
Step 3: Set up a route in routes/web.php to display this page:
Route::get('/home', function () { return view('pages.home', [ 'pageHeading' => 'Welcome to Our Homepage', 'userName' => 'Jane Doe' ]);});Step 4: Visit http://localhost:8000/home in your browser. You will see the homepage content rendered within the master layout structure, with the title, sidebar, and content sections populated from home.blade.php.
Blade provides many more features, including components, loops, conditional statements, and including sub-views. Refer to the official Laravel Blade documentation for a comprehensive guide.