Darama
Darama

Reputation: 3370

How to improve Laravel code using with operator?

In my request to DB I use Laravel's models and function with like:

$user = User::with("city")->get();

Problem is that if to do the following in template:

{{$user->city()->name}}

It will work only then if user specified city, so then value exists in database table. Otherwise it returns an error:

How to get rid of superfluous checks like:

@if(isset($user->city()->name))
   {{$user->city()->name}}
@endif

This is awfully!

Upvotes: 0

Views: 45

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219930

When defining the relationship on your model, use the withDefault method:

class User extends Model
{
    public function city()
    {
        return $this->hasOne(City::class)->withDefault();
    }
}

With this in place, $user->city will always return a City model.

Upvotes: 5

Related Questions