Blade views are stored in the resources/views
directory and use the .blade.php
file extension. They allow you to use plain PHP code in your views, which makes it super easy to manage and display dynamic data.
To create a Blade view, you simply create a new file in the resources/views
directory. For example, to create a view called welcome
, you would create a file named welcome.blade.php
.
To display data, you use curly braces {}
. The data must be passed to the view by the route or controller.
Example:
// Route
Route::get('/', function () {
return view('welcome', ['name' => 'Taylor']);
});
// View
Hello, {{ $name }}.
Blade offers several helpful control structures, like @if
, @foreach
, and @while
.
Example:
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
Let's see some practical examples.
You can create a layout with a yield section and then extend that layout in child views.
Example:
<!-- Stored in resources/views/layouts/app.blade.php -->
<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
<!-- Stored in resources/views/child.blade.php -->
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@parent
<p>This is appended to the master sidebar.</p>
@endsection
@section('content')
<p>This is my body content.</p>
@endsection
In the above example, the layout file app.blade.php
is specified with @extends
. The @section
directive is used to specify sections of content, while @yield
is used to display the contents of a given section.
In this tutorial, we covered Blade, the simple yet powerful templating engine provided with Laravel. We learned how to create Blade views and display data, how to use Blade’s control structures, and how to extend layouts. For further learning, consider exploring more complex Blade features like sub-views, components, and slots.
@foreach
loop to display each item.Hint: Use the @extends
, @section
, and @yield
directives to create and extend layouts.