Prevent Accessing Missing Attributes

  • Laravel
  • Eloquent

Have you ever tried to access a property on a Model that doesn't exist? By default Laravel will just return null, but if you want Laravel to throw an error you can:

1namespace App\Providers;
2 
3use Illuminate\Database\Eloquent\Model;
4use Illuminate\Support\ServiceProvider;
5 
6class AppServiceProvider extends ServiceProvider
7{
8 public function boot(): void
9 {
10 Model::preventAccessingMissingAttributes();
11 }
12}

If you try to access a property on a Model that doesn't exist, you'll get:

1The attribute [full_name] either does not exist or was not retrieved for model [App\Models\User].

This also works if you try to access a property on a model that exists, but is not loaded.