I'm using laravel 8 and when i write route like this:
web.php
Route::match(['get', 'post'], '/', [PageController::class, 'index']);
Route::match(['get', 'post'], '/tshirt', [PageController::class, 'productCategory']);
Route::match(['get', 'post'], '/electronic', [PageController::class, 'productCategory']);
Route::match(['get', 'post'], '/tshirt/{slug}', [PageController::class, 'detail']);
Route::match(['get', 'post'], '/electronic/{slug}', [PageController::class, 'detail']);
and controller like this:
PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PageController extends Controller
{
public function index()
{
$data = [
'title' => 'Dashboard',
];
return view('pages.index', $data);
}
public function productCategory($category)
{
# code...
}
public function detail($category, $detail)
{
# code...
}
}
what I want is if when the user is at the url '/tshirt' or '/electronic' then the thshirt or electronic will be included in the $category argument of PageController::productCategory
Similarly, when the user is typing '/tshirt/nameoftshirt' then the PageController::detail controller will fill the $category argument with 'tshirt' and $slug with 'nameoftshirt'
It shows this error:
ArgumentCountError
Too few arguments to function App\Http\Controllers\PageController::productCategory(), 0 passed in D:\Programing\Web\laraApp\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected
how to get route to pass main parameter to controller?
you have to make the main category dynamic and you can then catch it in your controller like you are trying right now.. this way you don't have to make routes for each category.
Route::match(['get', 'post'], '/{category}', [PageController::class, 'productCategory']);
Route::match(['get', 'post'], '/{category}/{slug}', [PageController::class, 'detail']);
and then in controller
public function productCategory($category)
{
dd($categoty); // prints tshirt when you hit the url /tshirt
}
public function detail($category, $detail)
{
dd($categoty, $detail); // prints tshirt and nameoftshirt when you hit the url /tshirt/nameoftshirt
}