Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help using all() and find() in the same function for Laravel

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)

like image 467
Ryan Lim Avatar asked Jul 09 '19 04:07

Ryan Lim


People also ask

Why we use -> Get in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

What is the difference between -> and => in Laravel?

-> and => are both operators. The difference is that => is the assign operator that is used while creating an array.

What is DD function in Laravel?

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.


1 Answers

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.

like image 60
Immeyti Avatar answered Oct 21 '22 20:10

Immeyti