Undefined variable despite variable being defined? - laravel

Users in my app can create their own groups. A Group is displayed on the groups/show.blade.php and other users can join said group(s).
I want to show a list of all people who have joined each group.
On the groups/show.blade.php page I have the following
#if ($joinedUsers)
#foreach($joinedUsers as $joinedUser)
{{$user->name}}
#endforeach
#else
#endif
#endsection
The error I get is:
Undefined variable: group_joined_user
which is strange because in my Group model I have
* Get the users that joined the group.
*/
public function joinedUsers()
{
return $this->belongsToMany(User::class, 'group_joined_user', 'group_id', 'user_id')
->withTimestamps();
}
And my GroupController.php
public function show($id)
{
$group = Group::with('joinedUsers')->where('id', $id)->first();
return view('groups.show', compact('group'));
}
I have this in my Routes
Route::resource('groups', 'GroupsController');
I'm fairly new to Laravel so I might be missing something obvious here?

you have defined $group variable only. joinedUsersis the relation and you never defined it as a variable anywhere. you have to do it like
#foreach($group->joinedUsers as $user)
{{$user->name}}
#endforeach

Related

How to fix Laravel resource is not working properly in blade view?

I'm confused why casted props are inaccessible in the blade file. When I try to check it in the controller its showing properly.
Here's the JSON shown in the browser: return $users; (here status is string)
But when I tried to show it in the view, the status goes back to int which is the original value.
#foreach ($users as $user)
<h1>{{ $user->status }}</h1>
#endforeach
And when I tried to dd in the blade view it shows the original model values.
Here's my resource file (shortened version):
public function toArray($request)
{
return [
'status' => StatusEnum::value($this->status),
...
];
}
Here's my controller look like:
public function index()
{
$record = User::all();
$users = UserResource::collection($record);
return view('pages.user.index', compact('users'));
}
I already tried solutions from other related QA e.g. ->resolve() but not working properly.
Make sure user model doesn't has getStatusAttribute() function nor status() if it returns a related model.
Keep in mind that this may be due to inherited or imported classes and traits in User model

Getting result only for a specified id in Eloquent

I have a little problem. My code is working, but I think I'm not doing it the proper way.
In my GradeController i have this code:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if(auth()->user()->hasRole('Student')) {
$subjects = Subject::all();
return view('grades.student.index', compact('subjects'));
}
}
And in my view I'm getting Grades which belong to a specified user this way:
#foreach($subject->grades->where('student_id', '=', auth()->user()->id) as $grade)
<span class="badge badge-primary">
{{ $grade->value }}
</span>#endforeach
Is here, I mean Laravel, any better way to do this? Because I think that getting all Grades which belong to a Subject and then look for ID is not very "effective".
Have a good day.
You can use the with() eager loading helper, with a closure which will filter the subject's 'grades` based on the grade belonging to the logged in user:
$subjects = Subject::with(['grades' => function($query) {
$query->where('student_id', auth()->user()->id);
}])->get();
Note the removal of , '=', in the ->where() clause. It does not need this argument if checking if equal to.
In your controller index() you can make a middleware instead of doing this check auth()->user()->hasRole('Student') many times, buy if you will check only once here it will be fine what you did.
public function index()
{
// refactoring
return view('grades.student.index', ['subject' => Subject::all()]);
}
Also its not good to make a query in your blade file, so you can pass grades directly from you controller
public function index()
{
return view('grades.student.index', [
'grades' => Grade::where('student_id', auth()->id())->get()
]);
}
In index blade file you can now use:
#foreach($grades as $grade)
<span class="badge badge-primary">
{{ $grade->value }}
</span>
// you can get the subject from $grade->subject
#endforeach

How to get name from eloquent model classes to my view

I'm trying to get name of a user using the following code, but i'm getting an error. please help. The error is
"Trying to get property 'name' of non-object (View: /var/www/html/laravel/imarker/resources/views/student/exams/available.blade.php)"
#foreach($availableExams as $exam)
#foreach($exam->user as $user)
{{($user->name)}}
#endforeach
#endforeach
Exam Model
public function user(){
return $this->belongsTo('App\User');
}
User Model
public function exams(){
return $this->hasMany('App\Exam');
}
Controller
public function availableExams(){
$users = User::all();
$availableExams = Exam::all();
return
view('student/exams/available',compact('availableExams', 'users'));
}
Each Exam has one User and that User has a name? Try this:
#foreach($availableExams as $exam)
{{$exam->user->name }}
#endforeach
Got it. One user was missing. using an if statement to check if the object exists solves it. Using 2 arrows risks finding an empty item/object and that causes problems, hence the need for the condition clause. Thank you guys.
#foreach($availableExams as $exam)
{{$exam->user->name ?? 'No tutor found'}}
#endforeach
Update your blade file.
#foreach($availableExams as $exam)
{{ $exam->user()->first()->name }}
#endforeach

Laravel access relation

I want to access a relation of the model when I get all the results but I keep getting the following error:
Undefined property: Illuminate\Database\Eloquent\Collection::$voornaam
Code:
- Model : Selectie.php
public function User()
{
return $this->hasMany('User', 'id', 'user_id');
}
- Controller
$selectie = Selectie::where('wedstrijd_id', '=', $id)->get();
return View::make('base.match.show')->with('selectie', $selectie);
- View
#foreach($selectie as $sel)
{{ $sel->user->voornaam }}
#endforeach
You have One to Many Relation in Selectie model. That means , $sel->user returns Collection Array , you cant reach array attributes like that.
#foreach($selectie as $sel)
#foreach($sel->user as $user)
{{ $user->voornaam }}
#endforeach
#endforeach
Try like this , otherwise you have to change your Selectie Model - User Model Relation type with One-To-One

Laravel - oneToMany returning Undefined property

I just searched for this problem in all posts but i cant get the answer.
I have 3 tables: users | categorys | sectors with the below model:
User.php
public function categorys(){
return $this->hasMany('Category');
}
Category.php
public function user(){
return $this->belongsTo('User');
}
public function sectors(){
return $this->hasMany('Sector');
}
Sector.php
public function category(){
return $this->belongsTo('Category');
}
Tables
users:
id,name
categorys:
id,name,user_id(fk)
sectors:
id,name,category_id(fk)
I want to print in a view all the sectors from authenticated user, with something like this:
$user = new User;
$user = Auth::user();
$sectors = $user->categorys->sectors;
and use this in $sectors variable in view
#foreach($sectors as $sector)
{{ $sector->id }}
{{ $sector->name }}
#endforeach
But i get this error:
Undefined property: Illuminate\Database\Eloquent\Collection::$sectors
Need help! Thanks
BR
Either you forgot to mention it in your article, or the sector_id field is missing in the categorys table.
According to your database structure there is no foreign key from table categorys to table sectors
As i mentioned before here is the answer for the above issue.
The hasmanythought relation is the correct way to relate and easy query thouse 3 tables.
For model User.php you need to create the relationship:
public function sectors(){
return $this->hasManyThrough('Sector','Category');
}
Now in your controller you need to do:
$user = new User;
$user = Auth::user();
$sectors = $user->sectors;
#return the view showsectors
return View::make('showsectors')->with('sectors', $sectors);
Use this variable (sectors) to print the query result (all sector's descriptions from one user) in your view, with something like the below:
#foreach($sectors as $sector)
{{ $sector->id }}
{{ $sector->description }}
#endforeach
Thanks for helping with this.
BR

Resources