Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Hi,

I'm really really new to Laravel (and up-to-date frameworks in general) and still doing the basic tutorials, but I got a similar question to such relationships.

The foreign id isn't always set, but nevertheless I want to use "belongsTo". On the other side, it is throwing me errors in the view, when I don't check the value of the forein id first.

To use the above example, is it a good idea to do something like this?

class Post extends Model
{
    public function editor()
    {
        return ($this->editor_id > 0) ? $this->belongsTo(User::class, 'editor_id') : new User;
    }
}

Edit: My suggestion is by the way not working. :( As a return type an instance of a relationship class is expected...

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.