How to Create Layout in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create layout in laravel.

 

How to create layout in laravel

Creating a layout in Laravel involves a few steps:

 

Step 1 - Create a Blade template for the layout: In Laravel, Blade is the templating engine used for creating views. You can create a Blade template file for your layout by using the `@yield` directive to define sections where the content of each page will be inserted. For example:

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

 

Step 2 - Extend the layout in your other views: Once you have created the layout template, you can extend it in your other views by using the `@extends` directive. For example:

@extends('layouts.app')

@section('title', 'Welcome')

@section('header')
    <h1>Welcome to my site</h1>
@endsection

@section('content')
    <p>This is the homepage</p>
@endsection

In this example, the `@extends` directive tells Laravel to use the `layouts.app` template as the base for this view. The `@section` directives define the content that will be inserted into the corresponding sections in the layout.

 

Step 3 - Use the layout in your controller: In your controller method, you can return a view that extends the layout like this:

public function index()
{
    return view('welcome');
}

In this example, the `welcome` view extends the `layouts.app` template, so the content defined in the `@section` directives will be inserted into the appropriate sections of the layout.

 

That's it! By following these steps, you can create a flexible and reusable layout for your Laravel application.

Comments 0

Leave a comment