octal's avatar
Level 1

What's the difference between @yield and @include

Hello, what's the difference between @yield and @include directives in blade?

I can't see any.

0 likes
6 replies
princeoo7's avatar

@yield will get only the specifed section of the file to which you are refering to like:

@section('content')
    lorem text
@endsection

@section('admin-content')
    some thing for admin only
@endsection

in your blade file:

@if(Auth::guest())
    @yeild('content')
@else   
    @yeild('admin-content')
@endif

but if you have a file which you fully want to include the we use @include and we don't need to specify what section from the file needs to be loaded and what not.

like:

//nav.php

<ul>
    <li>Home</li>

    <li>About Us</li>

    <li>Contact Us</li>
</ul>

i hope i was able to help :)

3 likes
octal's avatar
Level 1

@PRINCEOO7 - Ok, thanks. That answers my question.

So with include we blindly imports a full file and insert its content to the location of the @include directive.

With yield, we specify the file that serves as a (html page) content provider, and the yield will only consume the @section that has the name provided in the @yield directive.

Cobs's avatar

@include juste copy/paste a partial to the main layout

@yield use the template Inheritance. Personnally, I use a lot the section's overriding so i highly prefer @yield over @include.

princeoo7's avatar

@OCTAL - happy to help :)

just remember @yield is used in templating even if we can use it for other things. while in @include anything goes as it refers to native PHP include function.

this way when we have lots of imports to a single file. we can clearly tell what import / includes are for what purpose. makes life easier :D

Please or to participate in this conversation.