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 href="{{url('cars')}}" class="list-group-item">Vše</a>
@foreach($carsgroup as $group)
<a href="{{str_replace('S','Š',ucfirst(strtolower($group->znacka))) }}" class="list-group-item">{{ $group->znacka }}</a>
@endforeach
</div>
Route
Route::get('Renault', 'CarController@renault');
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}', 'CarController@carsbybrand');
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);
}