Laravel access relation - laravel

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

Related

Laravel : how to show CategoryTitle in show views from pivot table

I want show category_title in post views.i'm using pivot for category_id and post_id
Post Model:
public function categories()
{
return $this->belongsToMany(Category::class,'category_post','post_id','category_id');
}
Show.blade.php
{{$post->categories->category_title}}
but show me this error
Property [category_title] does not exist on this collection instance.
You can not access it directly, with belongsToMany you're getting multiple objects.
To access this you need to follow it as below.
#foreach($post->categories as $category)
{{ $category->category_title }}
#endforeach
Or you can access it as below.
{{ $post->categories->pluck('category_title ')->implode(',') }}

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.

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 5.3 access hasone in elequant from view

I'm trying to access a relations table from a collection of data passed in from the controller. I am able to iterate the collection in my view but I am unable to access the relationship data.
There are 2 tables:
stocks (default model)
stock_datas (has a foreign key stock_id which is already setup)
Controller:
public function getstock() {
return view('vehicles.getstock', ['stock' => \App\Stock::all()]);
}
Model (App\Stock) and then (App\StockData)
// From stock model:
public function stockdata() {
return $this->hasOne('App\StockData');
}
// Stock Data model:
public function stock() {
return $this->belongsTo('App\Stock');
}
View (loop):
#foreach ($stock as $k => $v)
{{ print_r($v->stockdata()->get())->year }}
#endforeach
When I try the query below, I get a
Undefined property: Illuminate\Database\Eloquent\Collection::$year (View: F:\websites\tempsite\resources\views\vehicles\getstock.blade.php)
However, year is a column in the stock_datas table.
I am also able to print_r data from the \App\StockData() table so the reference to the table is correct as doing print_r(\App\StockData::all()) from the controller does return all the rows as expected.
What am I doing wrong?
Since it's one to one relation, you should do it like this:
#foreach ($stock as $v)
{{ $v->stockdata->year }}
#endforeach
First one You have to change {{ print_r($v->stockdata()->get())->year }} this line, remove print_r. Next one in foreach loop you can do something like this
#foreach($stock as $one)
{{ $one->stockadata()->first()->year }}
#endforeach
For better solution you should check if isset $one->stockadata()->first()
and after that call ->year. Finally code should be like this
#foreach($stock as $one)
{{ isset($one->stockadata()->first()) : $one->stockadata()->first()->year : 'Default' }}
#endforeach
When calling get() method on any relationship You will always receive collection, no matter what relationship You have.
There are at least two (2) ways to solve Your problem:
1. $v->stockdata->year
2. $v->stockdata()->first()->year
I would suggest You to use first one, because Your stockdata has 1:1 relationship.
Good luck!
For example:
Stock.php model
class Stock extends Model
{
protected $primaryKey = 'id';
function stockdata() {
return $this->hasOne('App\StockDatas', 'id', 'stock_id');
}
public function getStock(){
return Stock::with('stockdata')->get();
}
}
In contriller
public function getstock(Stock $stock) {
return view('vehicles.getstock', ['stock' => $stock->getStock]);
}
view
#foreach ($stock as $k => $v)
{{ $v->stockdata->year }}
#endforeach

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