简体   繁体   中英

how can i use same route for two different controller function methods in laravel

how can i use same route for two different controller function methods in laravel

first controller

public function index()
{
    $comproducts = Comproduct::paginate(6);

    $items = Item::orderBy('name')->get();

    return view('computer', compact(['comproducts', 'items']));

}

second controller

public function index()
{
    return view('search.index');
}

i want to use these two different controller functions for one route.

This is my route name

Route::get('/computer', [

'uses' => 'ComputerProductsController@index',
'as' => 'computer.list'

]);

laravel needs somehow to identify which exactly method you want. for example you can pass the parameter, which will identify which method to call.

public function index(Request $request)
{
   // if param exists, call function from another controller
   if($request->has('callAnotherMethod')){
       return app('App\Http\Controllers\yourControllerHere')->index();
   }
   $comproducts = Comproduct::paginate(6);

   $items = Item::orderBy('name')->get();

   return view('computer', compact(['comproducts', 'items']));

}

You can't. If you want to add search functionality to your first controller's index page, you should determine which page to show inside your controller.

A possible example controller:

public function index(Illuminate\Http\Request $request)
{
    // If the URL contains a 'search' parameter
    // (eg. /computer?search=intel)
    if ($request->has('search')) {
        // Do some searching here and 
        // show the search results page
        return view('search.index');
    }

    $comproducts = Comproduct::paginate(6);

    $items = Item::orderBy('name')->get();

    return view('computer', compact(['comproducts', 'items']));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM