Reputation: 105
I have to display data from post table
based on user
. But, I always get error
Trying to get property 'id' of non-object
even though dd($user)
and dd($post)
return it right. dd($user)
return 1st row, dd($post)
return 1st row. When commenting all the 'dd' function , I got 'Trying to get property 'id' of non-object' at $post = post::find($user->id);
. However when I dd($post->article_title, $post->id)
,I do get the data
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
$post = post::find($user->id);
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
Upvotes: 0
Views: 349
Reputation: 98
It might be because $post = post::find($user->id); is returning null value at some stances.
Check if it is empty or not by using the function empty and try again.
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
if(!empty($user->id){
$post = post::find($user->id);
}
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
Upvotes: 0
Reputation: 302
use something like this:
$RMM_details = Company::where('branch', 'RMM')->get();
$RMM_details->transform(function($RMM)use($user){
$user = User::find($RMM->id);
$post = post::find($user->id);
return [
'title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
];
});
Upvotes: 0
Reputation: 807
Be aware, when you dd()
something it die at first iteration in foreach
, error may occurs in another iterates, maybe id 1 is exists in user but 3 or 4 is not.
Upvotes: 1