How to get data using foreign key in eloquent model? - php

I have model named 'PropertyLead' as,
class PropertyLead extends Model
{
public function leadPropertyDetails()
{
return $this->belongsTo('App\Models\Property\Property', 'Property_id','id');
}
public function user()
{
return $this->belongsTo('App\Models\Access\User\User','user_id','id');
}
public function propertyRatings()
{
return $this
->hasMany('App\Models\Property\PropertyRating','Property_id','Property_id');
}
}
In my controller I am trying to get data as ,
$leads = PropertyLead::with('leadPropertyDetails','user','propertyRatings')
->get();
Here in $leads variable i am getting all the data that I want but In 'propertyRatings' I am getting user_id and other details. I also want to get the name user who rated that property using that user_id in propertyRatings object. I am really troubled in this query. Thanks in advance.

Use nested eager loading syntax to load nested relationships:
PropertyLead::with('propertyRatings', 'propertyRatings.user', 'leadPropertyDetails', 'user')->get();
Then you be able to display user name with:
#foreach ($leads as $lead)
#foreach ($lead->propertyRatings as $propertyRating)
{{ $propertyRatings->user->name }}
#endforeach
#endforeach

Related

Laravel Eloquent fetch nested compact json data

I have two different Models
App\Models\Team;
and
App\Models\Member;
Where my Team Model has this function
public function memberList()
{
return $this->hasMany('App\Models\Member');
}
and I'm using this code to show it on my blade
$team = Team::with('memberList')->get();
return view('front.pages.custom-pages-index', compact('team'));
here's my columns for the tables
MemberTable
Team Table
Now I'm trying to access the compact data using this foreach
#if(count($team))
#foreach($team as $field)
//Name of Team
<h1>{{$field->name}}</h1>
//Member
....
#endforeach
#endif
This is the sample content of compact data when I tried to access the {{ $team }} on blade file
[{
"id":1,
"name":"Executive Team",
"created_at":"2020-05-26 04:38:27",
"updated_at":"2020-05-26 04:38:27",
"member_list":[{
"id":1,
"team_id":1,
"position":1,
"name":"Chris White, PH.D",
"member_position":"President, Founder and CEO",
...And other member per specific team
The problem is I want to fetch on blade the members per specific teams
UPDATE
When I tried at least to access the name inside of the member_list using foreach
$field->member_list->name
I'm getting an error like this
Trying to get property 'name' of non-object
Tried to var_dump($field->member_list)
Tried this #php dd($field->member_list); #endphp
Because member_list item of variable field is an array and "name" isn't a key of this array. You should use another loop for your member list inside of your main loop.
#if(count($team))
#foreach($team as $field)
//Name of Team
<h1>{{$field->name}}</h1>
//Member
#if(!empty($field->member_list) OR !is_null($field->memberlist))
#foreach($field->member_list as $member)
<h2>{{$member->name}}</h2>
#endforeach
#endif
#endforeach
#endif
In my Member.php (Model)
Added this
public function member()
{
return $this->belongsTo('App\Models\Team', 'id', 'team_id');
}
In my Team.php (Model)
public function memberList()
{
return $this->hasMany('App\Models\Member', 'team_id', 'id');
}
Controller
$team = Team::with('memberList')->get();
return view('front.pages.custom-pages-index', compact('team'));
Blade
#if(count($team) > 0)
#foreach($team as $field)
{{$field->name}}
#foreach($field->memberList as $member)
{{$member->image}}
#endforeach
#endforeach
#endif
Need to map first the Team and Member models using its Primary key and Foreign Keys
And call the json column memberList

Can't load model data into create() function (ERROR: Call to a member function with() on array)

I get this error when trying to load a table into my create() function so that the user can select from a list of team_names in the create user page: Call to a member function with() on array
Here is my UserController.php
use Illuminate\Http\Request;
use App\Game;
use App\User;
use App\Team;
...
public function create()
{
$pagetitle = 'Create User';
$teams = Team::orderBy('team_name', 'asc')->get();
if(auth()->user()->user_type !== 'admin'){
return redirect('/')->with('error', "You do not have access to the game you attempted to view.");
}
return view('pages.admin.users.create', compact('pagetitle')->with('teams', $teams));
}
Here is my create.blade.php
#if(count($teams) > 0)
#foreach($teams as $team)
<option value="{{$team->id}}">{{$team->team_name}}</option>
#endforeach
#else
<p>No teams found...</p>
#endif
Relationships really should not matter in this case, though I do have all of them properly set up.
For context: I'm creating a "User", but loading all of the "Team" names.
Any help is greatly appreciated.
compact('pagetitle')->with('teams', $teams) is wrong.
compact('pagetitle') returns an array. there is no function called with() on array.
To returns an array contains both pagetitle and teams you can use compact.
compact('pagetitle', 'teams');
That's it.
So,
return view('pages.admin.users.create', compact('pagetitle', 'teams'));
You can use compact() or with() to pass object to view.
return view('pages.admin.users.create',compact('pagetitle','teams'));
OR
return view('pages.admin.users.create')->with('pagetitle',$pagetitle)->with( 'teams',$teams);

Double foreach loop with where condition in laravel blade

I have relations like this
User->hasMany->reviews
Review->belongsTo->user
Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review
Now I try to display answers for specific review. My reviewAnswer table looks like:
Id, review ID, text
But the problem is when I do that:
#foreach($user->reviews as $data)
#foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
{{$answer->text}}
#endforeach
#endforeach
Then reviews displays okay, but I get the same answers for every review. How to repair that?
Make sure to check if all the relationships are correct. In this example, I assume that your models are stored in your app folder.
First, your User model should have reviews
public function reviews() {
return $this->hasMany("App\Review", "user_id", "id");
}
Next, set up your Review model to have answers
public function answers() {
return $this->hasMany("App\ReviewAnswer", "review_id", "id");
}
Then this is how you'll get all users with their respective reviews and answers
$users = User::with("reviews.answers")->get();
Finally, peform the loop in your view
#foreach($users as $user)
#foreach($user->reviews as $review)
#foreach($review->answers as $answer)
#endforeach
#endforeach
#endforeach
Try using the hasManyThrough() option which the eloquent models provide you.
Link: Laravel Eloquent Relations
This means in your case you would add:
class User extends Model {
public function reviewAnswers(
return $this->hasManyThrough(ReviewAnswer::class,Review::class);
)
}
and then simply access it in blade as:
#foreach($user->reviewAnswers() as $reviewAnswer) {
{{$reviewAnswer->text}}
}

A correct query to get data from 3 tables and show it as a single element in laravel?

Suppose I have 3 tables, posts, post_images, and post_links.
post.id is a foreign key in both post_images and post_links.
Each post have multiple images.
I need a data which contains post, its images and its links as single element/array item. If there are 3 posts, I need 3 arrays with each array containing the posts images and links.
My code so far,
$data = DB::table('posts')
->join('post_images','posts.id' ,'=', 'post_images.post_id')
->join('post_links','posts.id' ,'=', 'post_links.post_id')
->select('posts.*')
->get();
with the above query I am getting all the records joined, If i have 3 records with 3 images each, I am getting 9 records, I just need 3 posts with its data as its sub arrays.
Any suggestion?
Here is the PostImage model
class PostImage extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
}
Here is the PostLink model
class PostLink extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
}
Here is the Post model
class Post extends Model
{
public function links() {
return $this->hasMany(PostLink::class);
}
public function images() {
return $this->hasMany(PostImage::class);
}
}
In the view you can reach everything you need.
#foreach ($posts as $post)
{$post->title} <br>
#foreach ($post->links as $link)
{$link->url} <br>
#endforeach
#foreach ($post->images as $image)
{$image->src} <br>
#endforeach
#endforeach
And if you want use less queries you could use eager loading to fetch all this data the first time. Eager Loading Laravel
Should look something like this
$posts = Post::with('images','links')->get();
if you already have relation in model you just have to use with method like
$data = PostModel::with('post_images','post_links')->get();
make it dd($data) and look at this. hope it will work.
References: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

Getting data in a table with matching IDs to the pivot table in Laravel

I've got 3 tables, the users table, the image table, and the favorites table which works sort of like a pivot table, as all it has is ID, image_id, and user_id.
In my user model, I have:
public function FavoritedByMe() {
return $this->hasMany('CommendMe\Models\Favorite', 'user_id');
}
In my favorites controller, I have:
public function getFavorites($username) {
$user = User::where('username', $username)->first();
return view('user.favorites')
->with('user', $user);
}
and this works just fine if I want to get the IDs of all the images I've favorited:
#foreach ($user->FavoritedByMe as $favorite)
{{ $favorite->image_id }}
#endforeach
However, what I'd really like to be able to return the view with the images themselves. Something like:
$favImages = Images::where('id', $user->FavoritedByMe->image_id);
return view('user.favorites')
->with('user', $user)
->with('favImages', $favImages);
Now obviously this won't work, and will return the error:
ErrorException in FavoritesController.php line 54: Undefined property: Illuminate\Database\Eloquent\Collection::$image_id
but perhaps some kind of Eloquent relationship would? I've tried making those work but they just don't "click" in my head.
How could I make this work?
Thanks in advance!
In your Favorite model add this relationship:
public function image()
{
return $this->belongsTo('YourImageModel');
}
Then you can acces the image like this:
#foreach ($user->FavoritedImages as $favorite)
{{ $favorite->image->yourProperty }}
#endforeach
In the laravel's best practices you should call your FavoritedByMe relationship favorites since it's obviously related to the user.

Categories