Can't access object field after eager loading in Laravel 8 - php

When I'm trying to eager load my Model with relation like that:
$plants = Plant::with('history')
->get()
->where('user_id', auth()->id());
I want to modify those extracted dates with my function like that:
foreach ($plants as $plant) {
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
$plant->fertilized_at = self::getDateForHumans($plant->history->fertilized_at);
}
I get this kind of error:
ErrorException
Trying to get property 'watered_at' of non-object
but if I try to debug it by dd() function i get a positive result
dd(self::getDateForHumans($plant->history->watered_at));
dd() result
Does anybody know how to fix it or what is the workaround?

seems your history has no watered_at member, so it comes to this error.
Check first if you can access this member with
if(isset($plant->history->watered_at)){
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
}

Related

In laravel, get an errror when show the product items

I want to get some view data using laravel. here is my code:
public function brandsview($cate_url, $brand_url)
{
$brands = Brands::where('url',$brand_url)->first();
$brand_id = $brands->id;
$products = Products::where('brand_id',$brand_id)
->where('status','!=','Hide')
->where('status','Show')
->get();
return view('lokalproductspage.brands')
->with('brands', $brands)
->with('products', $products);
}
I get the error trying to get property 'id' of non-object. Please help me.
Looks like $brands return nothing, are you checked it?
If return of $brands is not stable may be u should add some checks before use attributes like 'id'
Change first() to firstOrFail(), which will let you know if you actually found a record. Normally your error suggests there was no record found. It is a nice way to show a 404 if the user put a bad url in.
$brands = Brands::where('url',$brand_url)->firstOrFail();

Collection does not return object on first() method

I have a code where I'm trying to get the first Object of eloquent collection objects with the "first()" method, but I'm getting a "trying to get property of non-object exception".
If I loop the collection with a foreach, there is no problem accessing the properties of each object.
But when I try to access the properties of the first record that I'm trying to get via "first()" method (I don't mind which object of the collection really), then I get that, what is returned, is not an object.
$movimientos =
Om_movimiento::with(['estado_om',
'om' => function($query)
{
$query- >with('legajo','legajo_cuadrilla','terminal.armario.central','tipo_trabajo_om');
}])
->where('id_om', '=', $request->get('id_om'))
->orderBy('created_at','asc')
->get();
foreach($movimientos as $m)
{
echo $m->fecha_movimiento;
} //->no error here
echo $movimientos->first()->fecha_movimiento; //->error trying to get "fecha_movimiento" property.
Am I missing something here?
You cannot access first() on $movimientos because it currently isn't returning a collection from the database. You can debug using a variable dump var_dump() (http://php.net/manual/en/function.var-dump.php) or die dump dd().

How to solve Object of class stdClass could not be converted to string while returning data into view in laravel?

This is my Laravel controller code
public function switchInfo($prisw, $secsw){
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->get();
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id)
->get();
return view('switchinfo.switchinfoview',compact('infolist'));
}
when this code executing it gives Object of class stdClass could not be converted to string error. How can i solve this? How can i pass my infolist into switchinfoview view without getting this error?
You can use pluck() to get value of a column.
Your first query should like this:
$cur_sw_pair_id = DB::table('sw_pairs')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->pluck('sw_pairs');
Keep the second query as it is.
Hope it will help.
The issue is that ->get() returns a collection, which is a 0-indexed collection of results (rows) from the database. In your case, you want to be using the following query:
$cur_sw_pair_id = DB::table('sw_pairs')
->select('sw_pair_id')
->where('pri_sw','=',$prisw)
->where('sec_sw','=',$secsw)
->first();
And then accessing the property sw_pair_id of $cur_sw_pair_id, like so:
$infolist = DB::table('cust_sw_pair')
->select('interface','pri_sw_vlan','sec_sw_vlan','pri_sw_admin_status','sec_sw_admin_status','description')
->where('sw_pair_id', '=', $cur_sw_pair_id->sw_pair_id)
->first();
Then, in your view, you can access all the properties (anything in the ->select() statement) of $infolist using $infolist->PROPERTY_HERE
Note that using ->first() is essentially using the same as ->get();, but you have to access the results of ->get() using an index, so
$cur_sw_pair_id[0]->sw_pair_id
Hope that provides some insight for you.

Eloquent and Pivot Tables in Laravel 4

I have a Poll table, a Students table, and a pivot table between them that includes a token and their three votes.
public function students()
{
return $this->belongsToMany('Student', 'polls_students')->withPivot('token','first','second','third');
}
While working out saving the poll results, I came across some odd behavior that I don't quite understand. I'm hoping somebody can explain what it is I'm missing:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
In the above code, the foreach loop will successfully display the token, where the second one throws the exception Undefined property: Illuminate\Database\Eloquent\Collection::$pivot
What am I missing? Are these two calls not logically creating the same object? How is 'pivot' working on the first and not the latter?
You first example:
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students()->where('students.id', '=', Input::get('student_id'))->get() as $student){
var_dump($student->pivot->token);
}
Here $poll->students() retrieves a collection and because of foreach loop you get a single object in your $student variable and you can use $student->pivot->token
You second example:
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->get();
var_dump($student->pivot->token);
Here you are doing same thing, using $poll->students() you are getting a collection but this time you are not using a loop and trying to do same thing using $student->pivot->token but it's not working because you didn't define any index from which you want to get the pivot->token, if you try something like this
$student->first()->pivot->token
Or maybe
$student->get(1)->pivot->token
Or maybe you can use first() instead of get() like this
$student = $poll->students()->where('students.id', '=', Input::get('student_id'))->first();
Then you can use
$student->pivot->token
Remember that, get() returns a collection even if there is only one record/model.
$poll = Poll::find(Input::get('poll_id'));
foreach($poll->students as $student){
var_dump($student->pivot->where('student_id',$student->id)->where('poll_id',$poll->id)->first()->token);
}

Query a relationship in Laravel with WHERE method

I have a model called "User", which "belongsToMany" Items.
This relationship works fine, so I can easily do something like this:
User::find(4)->items->find(1)->name
Now, I would like to do something like this:
User::find(4)->items->where('name', '=', 'stick')->get()
I would expect the code to return all the user's items with the name "stick", but unfortunately that is not what happens. I receive this error:
"Call to undefined method Illuminate\Database\Eloquent\Collection::where()"
I also tried to build a query scope:
public function scopeName($query, $name)
{
return $query->whereName($name);
}
The query scope works when I do something like this:
Item::name('SC')->get()
but
User::find(4)->items->name('SC')->get()
still does not work.
Can you help me returning all the user's items, which have the name 'stick'?
If you're looking to just get a single user's items named "stick", this is how you would do it:
$stickItems = Item::whereUserId(4)->whereName('stick')->get();
Here we are using Eloquent's dynamic where methods, but you could rewrite it like so:
$stickItems = Item::where('user_id', '=', 4)->where('name', '=', 'stick')->get();
That should get you what you want.
You have to call the items() method, not use the magic property:
User::find(4)->items()->where('name', 'stick')->get();
// ^^

Categories