Home > front end >  How to pass variables master layout blade in Laravel 8
How to pass variables master layout blade in Laravel 8

Time:11-11

I'm using Laravel 8, but don't seem to know which controller controls the layout master blade file. I have been able to pass variables to the sub-view (Profile page) file successfully but don't know how to achieve that with the layout view master blade.

I am trying to pass variables from a controller called ProfileController in app\Http\Controllers to the master blade layout. In the profile controller, I have a code that retrieves user profile data from the database.

$profileInfo = Profile::with('address')->where('id', '=', '1')->get();
return view('admin_pages.profile', compact('profileInfo'));

In the profiles table, I have names and image fields first_name, last_name, photo which I can access with a foreach loop from the data $profileInfo passed to the sub-view using

@foreach($profileInfo as $data)
{{ $data->first_name}}
@endforeach

and so on.

My master blade file is located at resources\views\layout\admin.blade.php. I want to be able to display the names and photo from the admin.blade.php so the logged in user can see their profile image when logged in even when they don't visit their profile page (sub-view) which is located at resources\views\admin_pages\profile.blade.php, extending the master blade (admin.blade.php).

Please kindly help out.

CodePudding user response:

Solution 1: You can pass variable from the blade file via the @extends as second argument function.

Controller:

public function index(){
$title='Sir/Madam';
return view('home',compact('title'));
}

Home.blade.php

  <?php
    @extends('layouts.admin', ['title' => $title])

Layout.master.blade.php

dd($title)

you will see results.

CodePudding user response:

I suggest you to learn about Laravel Component.

You can make the profile in admin layout with dynamic data, reusable without pass variable in every controller and route.

Create an Admin component with artisan:

php artisan make:component Profile

It will create a Profile.php as component controller and profile.blade.php

Open Profile.php and add this code:

public function render()
    {
        return view('components.profile', [
            'profile' => Profile::with('address')->where('id', '=', '1')->first();
        ]);
    }

Open profile.blade.php

<div>
  {{$profile->first_name}}
</div>

Now, render the Profile component on your template admin.

Replace

@foreach($profileInfo as $data)
{{ $data->first_name}}
@endforeach

with

<x-profile/>

You can learn more by reading blade documentation in this link

  • Related