Route::get('catalog/{catname}', [MainController::class, 'getCatalog'])->name('catalog.page');
Route::get('catalog/{catname}/{alias}', [MainController::class, 'getItemsForList'])->name('catalog.view.item');
When I click on the link /catalog/table/table-black-and-white, I get an error
Attempt to read property "alias" on null
During development, I connected the database via belongsToMany
AppModelsCatalog
public function items() : BelongsToMany
{
return $this->belongsToMany(Item::class);
}
AppModelsItem
public function catalogs() : BelongsToMany
{
return $this->belongstoMany(Catalog::class);
}
The controller has two entries for outputting information
public function getCatalog($alias)
{
$cats = Catalog::where('alias', $alias)->first();
$cats->items;
return view('template.sait.page.catalog', compact('cats'))->with('alias', $alias);
}
public function getItemsForList($alias)
{
$data = Item::where('alias', $alias)->with('catalogs')->first();
return view('template.sait.page.catalog.view', compact('data'))->with('alias', $alias);
}
And in the view I display it like this:
@foreach($cats->items as $item)
.....
.....
<a href="{{route(''catalog.view.item'', $item->alias)}}">env</a>
As far as I understand, there is an error in my controller, and apparently I also do not fully indicate the route in the view, since sometimes I still get the error of missing “alias” field
2
Answers
In both getCatalog and getItemsForList methods, you are using first() which will return null if no matching record is found. You need to check if $cats or $data is null before trying to access their properties or relationships.
On the hand there are 2 route parameters in the getItemsForList and you are passing just one.
Also correct you a tag link
The query didn’t find a matching
Catalog
with the provided alias in thegetCatalog
method, this indicates that the$cats
variable isnull
when trying to access thealias
property.Check if
$cats
is notnull
before accessing its properties.Update the
getItemsForList
methodModify variable names accordingly in the view
NB: The important things to note are you check if the
$cats
variable is not null, and if it is, you can choose to eitherabort
with a404
error or handle it differently.