Home > other >  What is the correct method to pass parameter to Laravel controller for filtering data?
What is the correct method to pass parameter to Laravel controller for filtering data?

Time:09-28

This is my code of route for getting data from Laravel backend.

Route::get('/get/card',[CardController::class,'getCardList'])->name('card.list');

I call it like below, http://127.0.0.1:8000/get/card

Controller code

public function getCardList()
{
   //code goes here
}

The above code is working fine. I'm trying to add a parameter for adding filtration as follows;

Route::get('/get/card{treeItemID?}',[CardController::class,'getCardList'])->name('card.list');

public function getCardList($treeItemID)
{
}

http://127.0.0.1:8000/get/card?treeItemID=1

But, I'm getting the error "Too few arguments to function app\Http\Controllers\CardController::getCardList()..."

Can anyone notice what's wrong with my code that gives the above error when the parameter is added? Any help would be highly appreciated.

CodePudding user response:

if you want to get data like below url, please replace your route and method like below and check again. http://127.0.0.1:8000/get/card?treeItemID=1

Route::get('/get/card',[CardController::class,'getCardList'])->name('card.list');

public function getCardList(Request $request){

  $treeItemID = $request->input('treeItemID');

  return $treeItemID;

}

CodePudding user response:

You can use get and post both type of request for filtering purpose.

Scenario 1 => If you want to hide some parameter inside request then you can use POST type of request where use can pass data in form data and get from request inside in controller.

Route::post('/get/card',[CardController::class,'getCardList'])->name('card.list');

public function getCardList(Request $request){
    $treeItemID = $request->treeItemID;
    return $treeItemID;
}

Scenario 2 => If you do want to hide some parameter inside the request then you can use GET type of request where use can pass data in url and get from request or get from parameter url inside in controller.

Route::get('/get/card/{treeItemID}',[CardController::class,'getCardList'])->name('card.list');

public function getCardList($treeItemID){
    $treeItemID = $treeItemID;
    return $treeItemID;
}
  • Related