can use foreign keys in my laravel project - php

i have 2 tables ( users and feedbacks ) . in the the 2nd table i have user_id as a foreign key and i'm trying to get the name of the user who made the feedback
in User.php :
public function feedbackuser()
{
return $this->hasMany('App\Feedback');
}
in the Feedback.php :
public function usersfeed(){
return $this->belongsTo('App\User','user_id');
}
i tried those to methodes in y view :
{{$feedbacks->yser_id->name}}
and
{{$feedback->user_id['name']}}
NB : this was working but when i added the relationships in phpmyadmin it stopped
i was using this code :
#foreach($users as $user)
#if ($user->id == $feedback->user_id)
{{$user->name}}
#endif
#endforeach

You have to query the relationship first then you can access the relational data.
Here is a pseudo code example:
{{ $user->feedbackuser->name }}
or the inverse of:
{{ $feedback->usersfeed->user_id }}

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

Laravel questions about using One to One relationship between 2 tables

I have 2 tables which is district and address. Suppose these 2 tables have relations between each other. address table holds district foreign key. The problem is that it returns null in views. How do I display/output the district name? I followed the instruction exactly based on Laravel documentation.
DISTRICT TABLE
District Model
public function address()
{
return $this->hasOne('App\Address');
}
ADDRESS TABLE
Address Model
public function district()
{
return $this->belongsTo('App\District', 'district');
}
View
$getAddress = App\Address::all();
foreach($getAddress as $add)
{
Address name: {{ $add->address_name }}
District name : {{ $add->district['district_name'] }} //this returns null, WHY?
}
Instead you should get all value in one stroke by using with
$getAddress = App\Address::with('district')->all();
And get value as
{{ $add->district->district_name }}
you should try this:
<php $getAddress = App\Address::with('district')->get(); ?>
#foreach($getAddress as $add)
Address name: {{ $add->address_name }}
#foreach($add->district as $districrt)
District name : {{ $districrt->district_name }}
#endforeach
#endforeach

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.

Laravel Checking If A Collection Contains A Foreign Key

I was wondering if there is a function or something else, where you can get an other element from a collection than the primary key... For example if votes would have a foreign key 'user_id', how do I check this? On the laravel doc there was only an example to check the primary key by using contains(). Can anyone help me out?
Example that checks if there is a vote with id = 2
#foreach($projects as $project)
#if ($project->votes->contains(2))
//
#endif
#endforeach
I would want something to check if there is a vote that has a 'user_id' = signed in users id
#foreach($projects as $project)
#if ($project->votes->contains('user_id' == Auth::id()))
//
#endif
#endforeach
if ($votes->contains('user_id', auth()->id())) {
//
}
In your model
public static checkForeign($thisId) {
( $thisId == Auth::user()->id ) ? return true : return false;
}
In the view
#if ( ModelName::checkForeign($project->votes->id) )
// Do something
#endif

Laravel Getting only certrain data from pivot table

I'm using Laravel to query users that have a score ( row in eventscore table )
And i want to return all the users that have scores for the event with an ID of 3
Is it possible to only return the score of every user, found in the pivot table ( see results below )
This is the code i'm using
$persons = Person::whereHas('eventscore', function($q) {
$q->where('id', 3);
})->with('eventscore')->get();
return $persons;
Thank you!
Try this:
// Person model
// accessor for easy fetching the score from the pivot model
public function getScoreAttribute()
{
return ($this->pivot && $this->pivot->score)
? $this->pivot->score
: null;
}
// example usage for the event's page (I assume participants is the relation)
$event = Event::with('participants')->find(3);
// somewhere in the view template
#foreach ($event->participants as $participant)
{{ $participant->name }} - score: {{ $participant->score }}
#endforeach

Categories