简体   繁体   中英

how to pass multiple table data to view in laravel 5.2

I have 3 tables in database,

--User

--Profile

--Education

User model

 public function profiledetails()
{
        return $this->hasOne('App\Profiledetails');
}

public function educationHasOne()
{
        return $this->hasOne('App\Education');
}

Profiledetails model

public function user()
{
        return $this->belongsTo('App\User');
}

Education model

public function user()
{
        return $this->belongsTo('App\User');
}

I am able to store the data.

I would like to view all table data in to one single webpage I use the below code to make that happen.

  public function index()
 {
 $user = Auth::user()->id;
 $profile = array(
     User::find($user)->profiledetails,
     User::find($user)->educationHasOne 
 );
 return view('profile.index', ['profile' => $profile]);
}

When is use dd($variablename), I am able to see all required field I needed,

Now, I would like to know how to pass all this data to view in single page.

You can pass an array to the view, like so:

return view('profile', ['profile' => $profile]);

In the view, you can access $profile .

If you need this data for each, it's recommend to use view composers . Nice documentation + examples can you find here: https://laravel.com/docs/5.1/views#passing-data-to-views

Thanks @Schellingerht, passing an array to the view work perfectly.

The code works perfect when user is logged in .

Below is my code

pass an array to the view

public function index()
{

 $user = Auth::user()->id;
 $profile   = User::find($user)->profiledetails;

 $education = User::find($user)->educationHasOne;
 return view('profile.index',['profile' => $profile, 'education' => $education]); 

}

you can use @Schellingerht answer or even use "compact"

$profile= 'someVar';
return view( 'profile',compact('profile') );

Here you dont need to create an assoc array. Just be sure that the variable name is the same as the string in compact. in your view you just call it with

{{$profile}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM