0

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?

1 Answers1

1

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
}
zahid hasan emon
  • 6,023
  • 3
  • 16
  • 28
  • so basically laravel can't catch the first url without category dynamic? Thanks for help – Tara Ivaldi Jul 25 '21 at 08:51
  • laravel can catch url parameter. not the static path. you can use other php function to get the url segments though. and if the answer helps, mark it as accepted. – zahid hasan emon Jul 25 '21 at 17:51