How to get name from eloquent model classes to my view - laravel

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

Related

How to dynamically switch between two arrays for attribute in my blade template

I have a controller method which retrieves data from a Queue, the queue can have a relationship to either a Guest or a Customer model.
In my blade template I iterate over the Queue and need to display either Guest.Name or Customer.Name depending on which column is populated.
Controller
$queue = Queue::where('business_id', '=', $business_id);
$customer_bag = $queue->pluck('user_id');
$guest_bag = $queue->pluck('guest_id');
$customers = User::whereIn('id', $customer_bag)->get();
$guests = Guest::whereIn('id', $guest_bag)->get();
return view('myqueue', compact(['queue', 'customers', 'guests']));
Blade Template
#foreach($queue as $quee)
{{ $customers->find($quee->user_id) ? $customers->find($quee->user_id)->name : $guests->find($quee->guest_id)->name }}
#endforeach
When I use this and the guest_id is blank I get an error stating "Trying to get property 'name' of non-object". How can I correctly detect which one to use?
I think so many problems with your code.
Firstly, $queue is findOrFail() which returns a single object data(not array or collection that can be used for foreach.) I think you need to change to get()
Also $customers and $guests are a collection, so you can not use find() method.
Then you didn't define $quee in the #foreach, so it's will give error result.
I think this code will return as you expected if you fix above problems:
#foreach($queue as $quee)
{{ \App\Customer::find($quee->user_id)->name ?? \App\Guest::find($quee->guest_id)->name ?? "no name" }}
#endforeach
But a better approach is using relation from your queue model:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function guest()
{
return $this->belongsTo(Guest::class);
}
public function getNameAttribute()
{
return $this->customer?$this->customer->name:($this->guest->name??"no name");
}
and in the blade view
#foreach($queue as $quee)
{{ $quee->name }}
#endforeach
The issue turned out to be that one of my test data records didn't have a value in the guest_id when it should have, this caused the blade template to fail render.

Laravel Nested Foreach for FAQ Views Trying to get property of non-object

i have a problem with my FAQ views. i want to display FAQ by categories like this:
Category1
FAQ1
FAQ2
FAQ3
Category2
FAQ1
FAQ2
FAQ3
Here is my Controller
public function faq()
{
$faq_category_vendor = DB::table('faq_categories')->where('categories_for','1')->get();
$faq_vendor = DB::table('faqs')
->join('faq_categories', 'faq_categories.id', '=', 'faqs.category')
->select('faqs.*','faq_categories.*', 'faq_categories.id as idcategory', 'faqs.id as id')
->where('faq_for','1')->get();
return view('owner.faq',['faq_category_vendor' => $faq_category_vendor,'faq_vendor' => $faq_vendor]);
}
Here is my Views :
#foreach($faq_category_vendor as $item)
For ({{$item->name}}) :
#foreach($faq_vendor as $item2)
#if ($item->id == $item2->category)
- {{$item2->ask}} : {{$item2->answer}}<br>
#else
#endif
#endforeach
<br>
#endforeach
The output is :
Facade\Ignition\Exceptions\ViewException
Trying to get property 'category' of non-object (View: C:\xampp\htdocs\weddinc\weddinc\weddinc_beta\resources\views\owner\faq.blade.php)
Can anyone help me?
Check if your faq_categories has id in faqs,becouse if don't you will get empty join so trying get
$item2->category
will throw exception.My proposition is do something like this in .blade
#php
try{
$testData=$item2->category;
} throw (\Exception $e) {
dd($item2);
}
#endphp
That will give you dd in blade so you will see if all records has joins
So there's a couple of points here which will help you out.
Your controller implies that you don't have relationships set up. Having relationships between your data will help you out massively; from what I can make out, you have a 1 to many relationship between faq_categories and faq (one faq_category has many faqs).
So, in your FaqCategory model:
public function faqs()
{
return $this->hasMany('app\faq');
}
In your Faq model:
public function category()
{
return $this->belongsTo('app\faq_category`);
}
Okay, so you said that you want to display each category, and then each FAQ under every category. In your controller, you can get all categories like so:
$categories = FaqCategory::all();
And in your blade, you can do this:
#foreach($categories as $category)
#foreach($category->faqs as $faq)
{{ $faq }}
#endforeach
#enforeach

Undefined variable despite variable being defined?

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

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