Reputation: 155
I got a slight issue,for some reason I'm unable to access my attributes from a relationship model.
I keep getting the same error, 'Undefined property: Illuminate\Database\Eloquent\Collection::$season'
I have been staring at this all day and I couldn't find a solution for it.
<?php namespace App\Http\Controllers;
use App\Show;
use App\Episode;
class TestController extends Controller {
public function test(){
$shows = Show::where('active',1)->get();
foreach ($shows as $show) {
if($show->active == 1 && $show->airday == date('N'))
{
echo 'test';
$episode = $show->episodes()->orderBy('id', 'desc')->take(1)->get();
\Debugbar::info($episode);
//this is the line where he gives me
echo('New episodes avaible, Season '.$episode->season.' Episode '.$episode->episode.' From '.$show->name);
//end error
}
}
}
}
?>
Although if I do a print out of the $episode variable I can clearly see the properties I wish to access.
Illuminate\Database\Eloquent\Collection {#150
#items: array:1 [
0 => App\Episode {#241
#table: "episodes"
+timestamps: true
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#original: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
At the moment I'm clueless whats wrong with the code. I hope someone can point me in the right direction.
Upvotes: 1
Views: 417
Reputation: 6920
When you call ->take(1)->get()
you're telling Eloquent (the builder, really) to give you back a Collection
object with 1 item in it.
So when you're trying to access your $season
property, you're actually trying to access it on a Collection object and not the Model that you think.
You can do a couple of things:
->take(1)->get()
call with ->first()
, $episode
variable as a collection, and retrieve the actual episode you care about by accessing $episode[0]
, first
on your current $episode
variable ($episode = $episode->first()
) to get the first model object within it.Upvotes: 2