Laravel 5.2 conditional extends template in Blade
Asked Answered
D

2

8

I want to extend template based on condition. I know i can use @if @else statement in blade. I am doing the same thing, but blade extending both the template. I don't know why.

@if(isset(Auth::user()->id))
    @extends('layouts.adminlayout')
@else
   @extends('layouts.default')
@endif

@section('content')
    i am the home page
    {{ isset(Auth::user()->id) }}
@stop

As, you can see i am checking whether or not user login-ed and then extend the template layout. But it is extending from both the layout.

Please help me.

Duong answered 4/3, 2016 at 9:31 Comment(0)
M
17

The first line in your extended blade view must be the @extends directive. Try using a ternary operator for this.

@extends(isset(Auth::user()->id) ? 'layouts.adminlayout' : 'layouts.default');

UPDATE for role based layouts. Refer to this question for more conditions.

@extends((!isset(Auth::user()->id))? 'layouts.default': ((Auth::user()->role == 'admin') ? 'layouts.adminlayout' : 'layouts.moderatorlayout'));
Malcommalcontent answered 4/3, 2016 at 9:36 Comment(6)
that's cool, what about is i have multiple condition like authenticated user based on role and why my condition not working.Duong
You can check users role on that condition.Malcommalcontent
could you please write that condition for admin and manager if user authenticated else default as i am not good with ternary operator.Duong
Let me try. If not possible i'll get back to you. Now i am accepting your question. But my one question still remaining, why my condition not work ?Duong
It's because The first line in your extended blade view must be the @extends directiveMalcommalcontent
is it possible to pass in variables to be included with the @extend call in this case when using a ternary statement?Commove
V
1

Try this code, parenterais are important

@extends(Auth::user()->rol_id == 1 ? 'layouts.admin' : ((Auth::user()->rol_id == 2) ? 'layouts.client' : 'layouts.client'))
Venality answered 11/11, 2020 at 2:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.