Reputation: 175
Very strange situation in Laravel 1 to Many relationships, My User model
public function reminder(){
return $this->hasMany(Reminder::class);
}
Reminder Model
public function user(){
return $this->belongsTo(User::class);
}
When I try to get
dd(auth()->user()->reminder) -> null
$user_id = auth()->user()->id;
$user = User::findOrFail($user_id);
dd($user->reminder) -> success I got results.
Question is why I can't get relationship result using auth()->user()->reminder
???
Upvotes: 0
Views: 79
Reputation: 175
Auth logged in user was actually given id from another table i.e Admin
Moving relationship to Admin Call did worked.
Upvotes: 0
Reputation: 3710
I've run not so fresh laravel 5.8 install with empty laravel. Both methods worked for me. I only had to be sure, that my user is logged in and the namespace is absolute. I've just put your code into routes/web. Here's my code:
Route::get('/', function () {
\Auth::loginUsingId(1);
dd(auth()->user()->reminder);
$user_id = auth()->user()->id;
$user = \App\User::findOrFail($user_id);
dd($user->reminder);
});
Please check if it helps you.
Upvotes: 1
Reputation: 31
Modify your public function reminder() to reminders(){.....} and additionally you can try also
public function reminders(){
return $this->hasMany(Reminder::class, 'user_id', 'id');
}
Upvotes: 1
Reputation: 91
You probably forgot to import your model class into the respective model
User.php
use App\Reminder;
public function reminders()
{
$this->hasMany(Reminder::class, 'user_id');
}
Upvotes: 1