Laravel Pivot table get value and pass to blade template - php

i'm trying to get all the Level_id and Term_id on my intermediate table using many to many relationship but i couldn't make it work and i want to pass it to my view using ordered list html.
i always end up with this..Trying to get property of non-object
Controller:
public function get_term_level()
{
$terms=Term::find(1);
foreach ($terms->level as $tm) {
$tm->pivot->Level_id;
}
return view('term_level.index',compact('terms'));
}
Term Model same as with my LevelModel
public function level(){
return $this->belongsToMany(Level::class, 'term_levels')->withPivot('Term_id', 'Level_id');
}
View
#foreach ($terms->pivot as $tm )
<ul>
<li>{{ $tm->Term_id }}</li>
{{ $tm->Level_id }}
</ul>#endforeach

Try this (inside your controller):
foreach ($terms->level()->get() as $tm) {
$tm->pivot->Level_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

Displaying data with many to many relationship laravel 6

I'm the beginner of laravel 6. I just want to ask. I want to display data but it doesn't show.
index.blade.php:
#if(isset($teachers))
#foreach($teachers->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endif
Controller:
public function index()
{
$teachers= DB::table('teachers')->first();
$qualifs = DB::table('qualifs')->find($teachers->id);
return view('teachers.index',compact('teachers','qualifs'));
}
qualif.php:
public function teachers()
{
return $this->belongsToMany('todolist\teacher', 'qualif_teachers');
}
teacher.php:
public function qualifs()
{
return $this->belongsToMany('todolist\qualif', 'qualif_teachers');
}
Note: Data is storing correctly, only displaying issue.
ERROR:Undefined property: stdClass::$qualifs
relationship belongs to a model instance that means to an eloquent object. when you are using query builder you will get stdObject instead of an eloquent object. and thus your relationship is not working. to make this work you have to use eloquent instead of query builder.
public function index()
{
$teachers= teacher::get();
return view('teachers.index',compact('teachers'));
}
and view will be like
#foreach($teachers as $teacher)
#foreach($teacher->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endforeach

How to get data using foreign key in eloquent model?

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

Triple Pivot Challenge

I have the following challenge, trying to join 3 tables in Laravel 5:
I have a many-to-many relation between 3 table: students, classrooms, terms. I would love to make a call like term->classroom->students.
I saw the Eloquent-triple-pivot package, but unfortunately, I cant get it working for Laravel 5.
Please, I would appreciate solution to bind this and make the call, eloquent or otherwise.
Thank you.
EDIT:
I have many-to-many relationship between 3 tables; classrooms, students, terms.
I have 3 pivot tables: classroom_term, classroom_student, student_term.
And 3 corresponding models: ClassroomTerm, ClassroomStudent, StudentTerm.
My Classroom model:
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
My Term Model:
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
My Student model:
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
What I am doing in my StudentsController is
$term = Term::findOrFail($id);
foreach($term->classrooms as $classroom) {
$studentids = ClassroomStudent::where('classroom_id', '=', $classroom->id)->get();
}
//to get the real student collection
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
return view('students.list')->with(['students' => $students]);
In my students.list view, I would simply want to retrieve students:
#foreach($students as $student)
First Name: {{!!$student->first_name!!}}
#endforeach
The error is in this line:
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
Undefined property: Illuminate\Database\Eloquent\Collection::$student_id'
However dd($studentids) returned an array and one of the attributes is student_id.
The code is cumbersome and not working.
Thanks for your help
The Goal:
To retrieve the students in the classroom in the term. With many-to-many relationship between classrooms, students and terms.
I think you could be setting the relations not well. Try thinking it well, for example, I think that probably a Student belongsTo a Classroom.
Classroom Model
public function students()
{
return $this->hasMany('App\Student')->withTimestamps();
}
public function terms()
{
return $this->belongsTo('App\Term')->withTimestamps();
}
Term Model:
public function classrooms()
{
return $this->hasMany('App\Classroom')->withTimestamps();
}
Student model:
public function classrooms()
{
return $this->belongsTo('App\Classroom')->withTimestamps();
}
An many to many relation returns an array which it still does when you define the sudentids ->get() also returns an array only ->first() would not return an array but then you do not get all students.
A variable does not turn in an array automatically making your foreach only return the last value.
So to correctly return the values from the students you would most likely get something like this.
Controller:
// Or even bind the term to the url
$term = Term::findOrFail($id);
return view('students.list',compact("term"));
View:
<!-- You could even remove the classroom name/list around it if you purely want to display all students under the term -->
<li>
#foreach($term->classrooms as $classroom) {
<ul>
Classroom: {{ $classroom->name }}
<li>
#foreach($classroom->students as $student)
<ul>
First name: {{ $student->first_name }}
</ul>
#endforeach
</li>
</ul>
#endforeach
</li>
Another simple way to return all students under a term is using the ->whereHas() in your query doing this would be enough
Controller:
$students = Student::whereHas("classrooms",function($q){
$q->whereHas("terms",function($q){
$q->where("id",$termId);
});
})->get();
return view('students.lists',compact("students"));
View:
<li>
#foreach($students as $student)
<ul>
First name: {{ $student->first_name }}
</ul>
#endforeach
</li>
If you want to return specific classrooms within a term or even a user under both you should create 3 controllers one for each of them (only 2 if you do not want to display students separate) and nest your classrooms under terms so you can simply type /terms/1/classrooms/2/ to get the right classroom or /terms/1/classrooms to get all classrooms under a term.

Getting Articles category laravel

I want to get category name of articles. This is my CategoriesController:
public function show(Category $category)
{
$articles = $category->articles()->latest()->paginate(5);
return view('categories.index', compact('articles'));
}
When I try to do it like this: {{$articles->category()}}
I'm getting this error: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\Eloquent\Collection' does not have a method 'category'
You already have the category getting passed to your controller action, so just pass that instance to your view rather than trying to grab it from every article item and potentially adding more database queries to your controller action.
public function show(Category $category)
{
return view('categories.index', compact('articles', 'category'));
}
$articles would, in this case, be a collection of several articles. Therefore you can't simply do {{ $articles->category }}.
This should work, however:
#foreach ($articles as $article)
{{ $article->category }}
#endforeach

Categories