Ad

List A Specific Item And Display Values Laravel

- 1 answer

I would like to ask how to improve the following code. I extract the brands of cars from the database, and then write them in the index template. If a user clicks on a specific brand, only the cars of that brand are displayed. I would like to improve the code using variables or a cycle, and I need help in doing so, therefore I attached at least a minimal working example of what I have already written.

CarController

public function index()
    {
        $cars = Car::latest()->get();
        $carsgroup = Car::whereNotNull('znacka')->groupBy('znacka')->orderBy('znacka', 'ASC')->get();

        return view('cars.index')
            ->with('cars', $cars)
            ->with('carsgroup', $carsgroup);

        }

public function renault()
    {
        $cars = Car::select()->where('znacka', 'Renault')->get();
        $carsgroup = Car::whereNotNull('znacka')->groupBy('znacka')->orderBy('znacka', 'ASC')->get();

        return view('cars.index')
            ->with('cars', $cars)
            ->with('carsgroup', $carsgroup);
    }

index.blade.php

<div class="list-group mb-5">
         <a target="_blank" rel="nofollow noreferrer" href="{{url('cars')}}" class="list-group-item">Vše</a>
            @foreach($carsgroup as $group)
               <a target="_blank" rel="nofollow noreferrer" href="{{str_replace('S','Š',ucfirst(strtolower($group->znacka))) }}" class="list-group-item">{{ $group->znacka }}</a>
            @endforeach
         </div>

Route

Route::get('Renault', '[email protected]');
Ad

Answer

In your routes/web.php you can add an additional parameter like this. If you want another url structure, you may have to adjust it a bit:

Route::get('cars/{brand}', '[email protected]');

This parameter can be accesses like this in your controller:

public function carsbybrand( $brand )
{
    $cars = Car::select()->where('znacka', $brand)->get();
    $carsgroup = Car::whereNotNull('znacka')->groupBy('znacka')->orderBy('znacka', 'ASC')->get();

    return view('cars.index')
        ->with('cars', $cars)
        ->with('carsgroup', $carsgroup);
}
Ad
source: stackoverflow.com
Ad