Set Default Value for Relationships in Laravel Models
When working with Laravel relationships sometimes the relationship returns null and triggers an error, so to avoid that we need to give the relationship a default value.
Set the default value for the relationship
We assume that we have a Post Model that belongs to a user that has been removed, and when we try to get the user's name through the relationship, we get an error 'trying to access property of non-object', so to solve this problem we give the relationship a default value for the user's name.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class)->withDefault([
'name' => 'N/A'
]);
}
}