when i run laravel project on my computer after doing php artisan serve as soon as it login it shows error "Attempt to read property "menus" on null"
Please help me
@foreach ($specials->menus as $menu)
<div class="max-w-xs mx-4 mb-2 rounded-lg shadow-lg">
<img class="w-full h-48" src="{{ Storage::url($menu->image) }}" alt="Image" />
<div class="px-6 py-4">
<h4 class="mb-3 text-xl font-semibold tracking-tight text-green-600 uppercase">
{{ $menu->name }}</h4>
<p class="leading-normal text-gray-700">{{ $menu->description }}.</p>
</div>
<div class="flex items-center justify-between p-4">
<span class="text-xl text-green-600">${{ $menu->price }}</span>
</div>
</div>
@endforeach
welcomecontroller.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Menu extends Model
{
use HasFactory;
protected $fillable = ['name', 'price', 'description', 'image'];
public function categories()
{
return $this->belongsToMany(Category::class, 'category_menu');
}
}
2
Answers
I suppose you forgot to initialize
$specials
, it is null, that’s why you get the error.Could you try to use
dd
beforeforeach
statement, so we can see it’s content?UPDATE:
Your issue is with this line of code (from the comments):
->first();
can returnnull
, so when you use it later as$specials->menus
, it can benull->menus
, which is not valid.You can use
->firstOrFail()
to trigger a 404 in the event$specials
results innull
, or@foreach($specials->menus ?? [] as $menu)
to short-circuit yourforeach()
with an empty array if$specials
isnull
:In your
Controller
:OR
In your
View
:Either case will properly handle your "unsafe" code (unsafe meaning functional, but possible for unhandled errors, like
null->menus
, etc.) and either trigger a404
before the view is rendered, or perform aforeach()
on an empty array, which does nothing.