Laravel eloquent relationships not working Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How does PHP 'foreach' actually work?Laravel hasManyThrough relationship with non-default local keyLaravel Migration foreign key errorLaravel 4 collecting data from relationshipLaravel, Eloquent n:m relationshipLaravel Eloquent relationship mapping issue with three tables and belongsTo() functionOne to many relationship in laravel extracting the latest timestampHow can I establish a relationship a Model class with another model class of folder in laravel eloquent??Laravel Eloquent relationship not workingLaravel hasMany and belongsTo parameters

What's the difference between using dependency injection with a container and using a service locator?

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

Economise space with floats

A strange hotel

Israeli soda type drink

Why did Israel vote against lifting the American embargo on Cuba?

Raising a bilingual kid. When should we introduce the majority language?

What is a 'Key' in computer science?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

With indentation set to `0em`, when using a line break, there is still an indentation of a size of a space

How to not starve gigantic beasts

How to open locks without disable device?

Are these square matrices always diagonalisable?

Suing a Police Officer Instead of the Police Department

Multiple options vs single option UI

Why is this method for solving linear equations systems using determinants works?

Co-worker works way more than he should

Is Bran literally the world's memory?

What is the ongoing value of the Kanban board to the developers as opposed to management

Retract an already submitted recommendation letter (written for an undergrad student)

Is accepting an invalid credit card number a security issue?

Did the Roman Empire have penal colonies?

My admission is revoked after accepting the admission offer

What to do with someone that cheated their way through university and a PhD program?



Laravel eloquent relationships not working



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How does PHP 'foreach' actually work?Laravel hasManyThrough relationship with non-default local keyLaravel Migration foreign key errorLaravel 4 collecting data from relationshipLaravel, Eloquent n:m relationshipLaravel Eloquent relationship mapping issue with three tables and belongsTo() functionOne to many relationship in laravel extracting the latest timestampHow can I establish a relationship a Model class with another model class of folder in laravel eloquent??Laravel Eloquent relationship not workingLaravel hasMany and belongsTo parameters



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have two tables as users and notifications, and I have a foreign key of notification_id in my users table, and in notifications.blade.php, I'm trying to get the user through id of notifications table as:



NotificationController:



public function notifications() 
$notifications = AppNotification::latest('created_at')->get();
return view('notifications', compact('notifications'));



notifications.blade.php:



@foreach ($notifications as $notification)
$notification->user->id
@endforeach


User.php(model):



public function notifications() 
return $this->hasMany('AppNotifications', 'notification_id');



Notification.php(model):



public function user() 
return $this->belongsTo('AppUser', 'notification_id');



Notifications table schema:



Schema::create('notifications', function (Blueprint $table) 
$table->engine = "InnoDB";
$table->increments('id');
$table->string('message');
$table->timestamps();
);


Users table schema:



Schema::create('users', function (Blueprint $table) 
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('notification_id')->nullable();
$table->foreign('notification_id')->references('id')->on('notifications');
);


but I'm getting Trying to get property of non-object error.










share|improve this question
























  • Can you post the entire error?

    – Jerodev
    Mar 22 at 15:59












  • Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

    – Usman Developer
    Mar 22 at 15:59







  • 1





    if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

    – TJ Weems
    Mar 22 at 16:01







  • 1





    So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

    – Chris Forrence
    Mar 22 at 16:14






  • 2





    Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

    – Chris Forrence
    Mar 22 at 16:23

















0















I have two tables as users and notifications, and I have a foreign key of notification_id in my users table, and in notifications.blade.php, I'm trying to get the user through id of notifications table as:



NotificationController:



public function notifications() 
$notifications = AppNotification::latest('created_at')->get();
return view('notifications', compact('notifications'));



notifications.blade.php:



@foreach ($notifications as $notification)
$notification->user->id
@endforeach


User.php(model):



public function notifications() 
return $this->hasMany('AppNotifications', 'notification_id');



Notification.php(model):



public function user() 
return $this->belongsTo('AppUser', 'notification_id');



Notifications table schema:



Schema::create('notifications', function (Blueprint $table) 
$table->engine = "InnoDB";
$table->increments('id');
$table->string('message');
$table->timestamps();
);


Users table schema:



Schema::create('users', function (Blueprint $table) 
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('notification_id')->nullable();
$table->foreign('notification_id')->references('id')->on('notifications');
);


but I'm getting Trying to get property of non-object error.










share|improve this question
























  • Can you post the entire error?

    – Jerodev
    Mar 22 at 15:59












  • Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

    – Usman Developer
    Mar 22 at 15:59







  • 1





    if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

    – TJ Weems
    Mar 22 at 16:01







  • 1





    So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

    – Chris Forrence
    Mar 22 at 16:14






  • 2





    Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

    – Chris Forrence
    Mar 22 at 16:23













0












0








0








I have two tables as users and notifications, and I have a foreign key of notification_id in my users table, and in notifications.blade.php, I'm trying to get the user through id of notifications table as:



NotificationController:



public function notifications() 
$notifications = AppNotification::latest('created_at')->get();
return view('notifications', compact('notifications'));



notifications.blade.php:



@foreach ($notifications as $notification)
$notification->user->id
@endforeach


User.php(model):



public function notifications() 
return $this->hasMany('AppNotifications', 'notification_id');



Notification.php(model):



public function user() 
return $this->belongsTo('AppUser', 'notification_id');



Notifications table schema:



Schema::create('notifications', function (Blueprint $table) 
$table->engine = "InnoDB";
$table->increments('id');
$table->string('message');
$table->timestamps();
);


Users table schema:



Schema::create('users', function (Blueprint $table) 
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('notification_id')->nullable();
$table->foreign('notification_id')->references('id')->on('notifications');
);


but I'm getting Trying to get property of non-object error.










share|improve this question
















I have two tables as users and notifications, and I have a foreign key of notification_id in my users table, and in notifications.blade.php, I'm trying to get the user through id of notifications table as:



NotificationController:



public function notifications() 
$notifications = AppNotification::latest('created_at')->get();
return view('notifications', compact('notifications'));



notifications.blade.php:



@foreach ($notifications as $notification)
$notification->user->id
@endforeach


User.php(model):



public function notifications() 
return $this->hasMany('AppNotifications', 'notification_id');



Notification.php(model):



public function user() 
return $this->belongsTo('AppUser', 'notification_id');



Notifications table schema:



Schema::create('notifications', function (Blueprint $table) 
$table->engine = "InnoDB";
$table->increments('id');
$table->string('message');
$table->timestamps();
);


Users table schema:



Schema::create('users', function (Blueprint $table) 
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->unsignedInteger('notification_id')->nullable();
$table->foreign('notification_id')->references('id')->on('notifications');
);


but I'm getting Trying to get property of non-object error.







php laravel orm foreign-keys






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 16:17







Usman Developer

















asked Mar 22 at 15:55









Usman DeveloperUsman Developer

30015




30015












  • Can you post the entire error?

    – Jerodev
    Mar 22 at 15:59












  • Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

    – Usman Developer
    Mar 22 at 15:59







  • 1





    if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

    – TJ Weems
    Mar 22 at 16:01







  • 1





    So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

    – Chris Forrence
    Mar 22 at 16:14






  • 2





    Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

    – Chris Forrence
    Mar 22 at 16:23

















  • Can you post the entire error?

    – Jerodev
    Mar 22 at 15:59












  • Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

    – Usman Developer
    Mar 22 at 15:59







  • 1





    if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

    – TJ Weems
    Mar 22 at 16:01







  • 1





    So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

    – Chris Forrence
    Mar 22 at 16:14






  • 2





    Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

    – Chris Forrence
    Mar 22 at 16:23
















Can you post the entire error?

– Jerodev
Mar 22 at 15:59






Can you post the entire error?

– Jerodev
Mar 22 at 15:59














Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

– Usman Developer
Mar 22 at 15:59






Trying to get property of non-object (View: D:WampServerwwwDigitalInvigilatorresourcesviewsadminnotifications.blade.php)

– Usman Developer
Mar 22 at 15:59





1




1





if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

– TJ Weems
Mar 22 at 16:01






if notifications belongsTo a user, I believe you should have your foreign key on your notifications table as "user_id". you could try dd($notifications) to see what the controller is trying to return.

– TJ Weems
Mar 22 at 16:01





1




1





So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

– Chris Forrence
Mar 22 at 16:14





So while this won't fix this specific issue, that's going to be an issue with a hasMany relationship on your User (since that implies that a user has many notifications); will wait for the schemas

– Chris Forrence
Mar 22 at 16:14




2




2





Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

– Chris Forrence
Mar 22 at 16:23





Yep. Basically, with your database definition, a notification is essentially the parent record of a user, so your User model would have a belongsTo relationship with Notification, while your Notification model would have a hasMany relationship with User.

– Chris Forrence
Mar 22 at 16:23












2 Answers
2






active

oldest

votes


















1














the foreign key must be in Notification model (user_id) instead User model.
because your relationship say that



EDIT:



your code must be like this:
User.php(model):



public function notifications() 
return $this->hasMany('AppNotification', 'user_id');



Notification.php(model):



public function user() 
return $this->belongsTo('AppUser', 'user_id');



Notifications table schema:



Schema::create('notifications', function (Blueprint $table) 
$table->engine = "InnoDB";
$table->increments('id');
$table->string('message');
$table->timestamps();
$table->unsignedInteger('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('user');
);


Users table schema:



Schema::create('users', function (Blueprint $table) 
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
);





share|improve this answer

























  • I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

    – Usman Developer
    Mar 22 at 16:06






  • 3





    No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

    – otosankf
    Mar 22 at 16:14


















0














I have fixed this issue, thanks to Chris Forrence, I have changed the relation-ship as Chris Forrence said.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303453%2flaravel-eloquent-relationships-not-working%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    the foreign key must be in Notification model (user_id) instead User model.
    because your relationship say that



    EDIT:



    your code must be like this:
    User.php(model):



    public function notifications() 
    return $this->hasMany('AppNotification', 'user_id');



    Notification.php(model):



    public function user() 
    return $this->belongsTo('AppUser', 'user_id');



    Notifications table schema:



    Schema::create('notifications', function (Blueprint $table) 
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
    $table->unsignedInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('user');
    );


    Users table schema:



    Schema::create('users', function (Blueprint $table) 
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    );





    share|improve this answer

























    • I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

      – Usman Developer
      Mar 22 at 16:06






    • 3





      No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

      – otosankf
      Mar 22 at 16:14















    1














    the foreign key must be in Notification model (user_id) instead User model.
    because your relationship say that



    EDIT:



    your code must be like this:
    User.php(model):



    public function notifications() 
    return $this->hasMany('AppNotification', 'user_id');



    Notification.php(model):



    public function user() 
    return $this->belongsTo('AppUser', 'user_id');



    Notifications table schema:



    Schema::create('notifications', function (Blueprint $table) 
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
    $table->unsignedInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('user');
    );


    Users table schema:



    Schema::create('users', function (Blueprint $table) 
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    );





    share|improve this answer

























    • I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

      – Usman Developer
      Mar 22 at 16:06






    • 3





      No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

      – otosankf
      Mar 22 at 16:14













    1












    1








    1







    the foreign key must be in Notification model (user_id) instead User model.
    because your relationship say that



    EDIT:



    your code must be like this:
    User.php(model):



    public function notifications() 
    return $this->hasMany('AppNotification', 'user_id');



    Notification.php(model):



    public function user() 
    return $this->belongsTo('AppUser', 'user_id');



    Notifications table schema:



    Schema::create('notifications', function (Blueprint $table) 
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
    $table->unsignedInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('user');
    );


    Users table schema:



    Schema::create('users', function (Blueprint $table) 
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    );





    share|improve this answer















    the foreign key must be in Notification model (user_id) instead User model.
    because your relationship say that



    EDIT:



    your code must be like this:
    User.php(model):



    public function notifications() 
    return $this->hasMany('AppNotification', 'user_id');



    Notification.php(model):



    public function user() 
    return $this->belongsTo('AppUser', 'user_id');



    Notifications table schema:



    Schema::create('notifications', function (Blueprint $table) 
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
    $table->unsignedInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('user');
    );


    Users table schema:



    Schema::create('users', function (Blueprint $table) 
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    );






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 22 at 19:03

























    answered Mar 22 at 16:04









    otosankfotosankf

    362




    362












    • I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

      – Usman Developer
      Mar 22 at 16:06






    • 3





      No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

      – otosankf
      Mar 22 at 16:14

















    • I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

      – Usman Developer
      Mar 22 at 16:06






    • 3





      No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

      – otosankf
      Mar 22 at 16:14
















    I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

    – Usman Developer
    Mar 22 at 16:06





    I can't change the foreign key, can you make relationship for my existing code? as notification_id foreign key

    – Usman Developer
    Mar 22 at 16:06




    3




    3





    No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

    – otosankf
    Mar 22 at 16:14





    No. You can not do rhat you want whitout changue tje tables. Because the relationship that you want to use is a one (user) to many(norification) and this meaning that your foreign key MUST be in your "many side" model(notification)

    – otosankf
    Mar 22 at 16:14













    0














    I have fixed this issue, thanks to Chris Forrence, I have changed the relation-ship as Chris Forrence said.






    share|improve this answer



























      0














      I have fixed this issue, thanks to Chris Forrence, I have changed the relation-ship as Chris Forrence said.






      share|improve this answer

























        0












        0








        0







        I have fixed this issue, thanks to Chris Forrence, I have changed the relation-ship as Chris Forrence said.






        share|improve this answer













        I have fixed this issue, thanks to Chris Forrence, I have changed the relation-ship as Chris Forrence said.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 5:34









        Usman DeveloperUsman Developer

        30015




        30015



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55303453%2flaravel-eloquent-relationships-not-working%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript