What is the difference between @yield and @include in Laravel?

Question:

I'm learning Laravel 5.3 , @yield and @include look pretty much the same to me, the only difference I know of is that @include injects the parent's variables and can also include other variables.

  • What is the difference between @yield and @include ?
  • When should I use @yield ?
  • When should I use @include ?

Answer:

@yield is used to display the content of a given section, which is defined by @section which is responsible for defining a content section. An example are the templates that will serve as a basis for several pages.

Example administrative sector :

master.blade.php ( template ):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">    
</head>
<body>
<div class="container">
    <div class="panel panel-default">        
        <div class="panel-body">
            @yield('content')
        </div>
    </div>
</div>
</body>
</html>

roles.blade.php:

@extends('master')
@section('content')
    //Contéudo que será diferente para outras páginas
@stop

in this example, there is a base structure for all pages that will use a template is with @section is where the content will be displayed in the template where it is @yield , in this case there is a relationship between these blade . @yield is used when you need to define sections in a template ( or page ) and to work it needs the corresponding @section have content to be loaded.

There are some codes where @yield is used simply as a value pass, example :

@yield('titulo')

e

@section('titulo', 'Novo titulo');

they are usually used as subtitles of these other views .


@include allows you to load other views ( sub-views with the extension nomenclature .blade.php ) into a view and use the variables that were sent to that view .

Example :

erros.blade.php

@if(isset($errors) && count($errors))
    <div class="alert alert-danger" style="margin-top: 6px;">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

cadastro.blade.php

@extends('master')
@section('content')
    @include('errors')
@stop

this @include is very particular to the registration pages of any table, where the data will be processed and validated and if there is any error this code snippet displays the messages of validation problems.

@include is different in these respects than @yield , because @include is to include a specific page, whereas @yield is to display content from a given section, which can also contain @include .

References

Scroll to Top