Muhammad Tariq
Muhammad Tariq

Reputation: 175

Laravel strange behavior in 1 to Many relationship

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

Answers (4)

Muhammad Tariq
Muhammad Tariq

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

cssBlaster21895
cssBlaster21895

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

M. Kamrul H.
M. Kamrul H.

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

Syahnur Nizam
Syahnur Nizam

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

Related Questions