sanainfotech February 2016

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.

Answers


schellingerht February 2016

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


Maky February 2016

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}}


sanainfotech February 2016

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]); 

}

Post Status

Asked in February 2016
Viewed 1,614 times
Voted 7
Answered 3 times

Search




Leave an answer