How to Use Blade Templates in Laravel (Layouts & Components)

Blade is Laravel's built-in template engine that makes writing HTML views clean and powerful. With Blade, you can create reusable layouts and components and display data with conci...

How to Use Blade Templates in Laravel (Layouts & Components)

Blade is Laravel's built-in template engine that makes writing HTML views clean and powerful. With Blade, you can create reusable layouts and components and display data with concise syntax. This article covers the basics.

Displaying Data

Use double curly braces to display a variable. Blade automatically escapes the output for security (preventing XSS):

<h1>{{ $title }}</h1>
<p>Hello, {{ $user->name }}</p>

Conditionals and Loops

@if ($posts->count())
    @foreach ($posts as $post)
        <h3>{{ $post->title }}</h3>
    @endforeach
@else
    <p>No articles yet.</p>
@endif

Blade also has @forelse, which combines a loop with an empty condition:

@forelse ($posts as $post)
    <li>{{ $post->title }}</li>
@empty
    <li>No data</li>
@endforelse

Creating a Layout with @extends

Create a parent layout, e.g. resources/views/layouts/app.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    @yield('content')
</body>
</html>

Then a child page simply fills in the defined sections:

@extends('layouts.app')

@section('title', 'Home')

@section('content')
    <h1>Welcome</h1>
@endsection

Including Partials with @include

For repeated pieces such as a navbar or footer:

@include('partials.navbar')

Blade Components (Reusable)

For elements used repeatedly with different data, create a component:

php artisan make:component Alert

Use it in a view:

<x-alert type="success" message="Data saved!" />

Displaying HTML Without Escaping

If you need to display raw HTML (e.g. article content from an editor), use the unescaped syntax — only for trusted sources:

{!! $post->content !!}

Conclusion

Blade keeps Laravel views tidy and easy to maintain: {{ }} for data, @extends/@section for layouts, and @include and components for reusable parts. Master these and your application's front-end structure will be far cleaner. To speed up view loading, check out our Laravel performance optimization guide.

blade template laravel blade laravel layout blade component blade laravel cara pakai blade laravel
Read Also

Here are some related articles that might help expand your knowledge:

Share this article
Back to Blog
🚀 Partner Recommendation

Need Premium Source Code & Business Apps?

Access Laravel applications, POS systems, School Management, Clinic Software, ERP solutions, and ready-to-use premium source code at GudangCode.

GudangCode
  • ✔ Premium Source Code
  • ✔ Ready-to-Use Systems
  • ✔ Lifetime Updates
  • ✔ Lifetime Membership
  • ✔ Daily App Updates
Join Membership →