Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Eloquent Data to blade component?

Hello,

I have a blade Layout called: profile.blade.php // component

And I have a blade file infos which extends from profile.blade.php component. On my controller, I have a profile method:

public method profile(User $user) {
   return view('infos.blade.php', compact('user'));
}

When I try to use the variable user to the profile.blade.php component, I have an error that says "undefined user variable"

My question is how can I get the data I received from my controller to Blade Component profle ? Because that part of component will be used many times.

Thanks.

like image 904
Artizan Avatar asked Nov 18 '25 08:11

Artizan


1 Answers

in your app/view/components/profile-

  <?php

namespace App\View\Components;

use Illuminate\View\Component;

class profile extends Component
{

   public $user; //for consistency

   public function __construct($user)
   {
       $this->user = $user;
   }


   public function render()
   {
       return view('components.profile');
   }
 }

now the component can render a variable ($user), in your info's blade/infos.blade.php you can feed the variable to the component like --

<x-profile :user='$user' ></x-profile>

i understand the question was posted quite a long ago but i had the same issue and the answers posted here didn't work for me but this method did so.....it may help somebody.

like image 126
Meraj Avatar answered Nov 21 '25 06:11

Meraj