Muhammad Haris
Muhammad Haris

Reputation: 310

RelationNotFoundException Call to undefined relationship [userStories] on model [App\User]

I have created a relationship between User model and StoryModel. But it give me the Error:-

Call to undefined relationship [userStories] on model [App\User].

May be I'm missing something. Following is my code which I'm using

Error image here

User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notification;
use App\CheckIn;
use App\Travel;
use Carbon\Carbon;
use App\NewInterest;
use App\UserStory;

class User extends Authenticatable
{
    use Notifiable;
    protected $table = "users";
    protected $primaryKey = 'id';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname','lastname', 'user_id','email',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function userStories(){
        return $this->hasMany(UserStory::class, 'user_id', 'user_id');
    }
}

Controller Logic

$usersStories = User::with('userStories')
                            ->select('id','user_id','stories')
                            ->get();
 print_r($usersStories);
    exit;

Upvotes: 1

Views: 3714

Answers (3)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should update your model and try:

User model

public function userStories(){
        return $this->hasMany(UserStory::class);
    }

UserStory model

public function users(){
        return $this->belongsTo(User::class, 'user_id');
    }

Upvotes: 1

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

Can you try by changing the sequence like this:

 $usersStories = User::->select('id','user_id','stories')
                       ->with('userStories')
                       ->get();
 print_r($usersStories);
 exit;

Upvotes: 1

Awadhesh Kumar
Awadhesh Kumar

Reputation: 420

Are you wriiten mapping code in your UserStory Model that should be

public function userAccount(){
        return $this->belongsTo(User::class);
    }

If you already written this code then check you column names in your DB.

Upvotes: 1

Related Questions