ホーム > Laravel > Laravel Change layouts to load depending on the type of Auth guard being authenticated
Laravel

Laravel Change layouts to load depending on the type of Auth guard being authenticated

Thank you for your continued support.
This article contains advertisements that help fund our operations.

Introduction

I've summarized a method to change the layouts to be loaded based on the guard for login authentication.

For example, when implementing multi-authentication, it's like creating a page where you want to display the same blade but with different common layouts like the Header.

Prerequisite Knowledge

Usually, it's loaded in the order of middleware->controller->blade, and then you write HTML in the blade.

Blade is useful because you can write PHP with @, but since it's a framework, there are certain conventions.

For example, this:

@extends("layouts.app")

This is the protagonist this time.

This child is read first when Blade is called.

Method tried without any research (Failed example)

@if(Auth::guard('user'))
 @extends('layouts.app')
@else
 @extends('layouts.admin')
@endif

I thought I was instructing to load the layout named app if logged in as a user.

As I said at the beginning, @extends is called first, so in reality:

@extends('layouts.app')
@extends('layouts.admin')

@if
@else
@endif

It didn't control anything because of the order.

Two layouts were called, and Golden Week became a surprise.

Successful example

Specify the name of the layout to be called in the controller.

In other words, for users, pass the name 'layouts.app', and for admins, pass the name 'layouts.admin' as a variable.

//Controller

public function index()
{
 if(Auth::guard('user')){
 $layout = 'layouts.user';
 } elseif(Auth::guard('admin')){
 $layout = 'layouts.admin';
 } else {
 return redirect()->route('home');
}
 return view('index',['layout'=>$layout]);
}

//Blade

@extends($layout)

Yes! It worked!

In the controller, I tried writing "if the user logs in" or "if the admin logs in" or "otherwise."

Simply pass a string and use it in extends in the Blade.

Simple and easy!

Summary

Laravel is super useful, but it can be quite difficult to remember the loading order and types, so let's work hard to crush each one and create explosive speed prototypes!!

For feedback or complaints, please contact me via TwitterDM.

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!