Blade files are stored in the resources/views/
directory and use the .blade.php
extension.
π Example: Creating home.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Blade</title>
</head>
<body>
<h1>Welcome to Laravel Blade!</h1>
</body>
</html>
This is a basic Blade template that serves as a view.
You can return a Blade template from a controller.
π Example: HomeController.php
namespace App\Http\Controllers;
class HomeController extends Controller {
public function index() {
return view('home'); // Renders home.blade.php
}
}
π Route Definition in web.php
Route::get('/home', [HomeController::class, 'index']);
Visiting /home
will display home.blade.php
.
Blade provides a clean syntax for embedding PHP.
π Example: Displaying a variable
<h1>Welcome, {{ $name }}</h1>
π Example: Conditional Rendering
@if($user == 'Admin')
<p>Welcome, Admin!</p>
@else
<p>Welcome, Guest!</p>
@endif
π Example: Looping through data
@foreach($users as $user)
<p>{{ $user }}</p>
@endforeach
Blade allows defining layouts for consistent structure.
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
π Example: home.blade.php
(Using Layout)
@extends('layout')
@section('title', 'Home Page')
@section('content')
<h1>Welcome to My Website</h1>
@endsection
This inherits the layout, reducing duplicate code.
Blade makes Laravel templating easy, flexible, and efficient by using layouts, components, and directives.
π― Next Steps: Learn about Blade Components, Directives, and @include! π
π Example: layout.blade.php
(Master Layout)