In my layouts, I am displaying all the categories (from my database) using a foreach statement. In the page, it is a page is it shown from the show() function. It seems a little contradicting because I have to use all() for the layout, and find() in the page. Is there any way to work around this?
public function show($id)
{
$categories = category::find($id);
$products = product::all()->sortBy('ID');
$categories = category::all()->sortBy('ID');
return view('categories', compact('products','categories'));
}
In the template
@foreach($categories as $category)
<li class="text-uppercase" style="white-space: nowrap;"><a href="{{ route('category.show', $category->id) }}">{{ $category->name}}</a></li>
@endforeach
In the page itself ( localhost:8000/category/5 ) I just want to display the name of the category in the page, not display all like in the above code block.
{{ $categories->name}}
When I put both the all() and find() into the same function
This is the error message:-
Property [name] does not exist on this collection instance. (View: C:.............\resources\views\categories.blade.php)
This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.
-> and => are both operators. The difference is that => is the assign operator that is used while creating an array.
dd stands for "Dump and Die." Laravel's dd() function can be defined as a helper function, which is used to dump a variable's contents to the browser and prevent the further script execution.
Your problem is you've been overwritten your $categories
variable. Once you populate it with single category (via find()
) then you override it with all categories (via all()
).
You should override your show()
function
public function show($id)
{
$category = category::find($id);
$products = product::all()->sortBy('ID');
$categories = category::all()->sortBy('ID');
return view('categories', compact('products','categories', 'category'));
}
You should use $categories
variable to get all categories and use $category
for getting a single category.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With