mercredi 5 août 2020

In Laravel, how can i return a specific *column* from a *table* inside my API Controller ? I'm using Laravel 5

Question

How can i return a specific column from a table [within the API Controller] ? I used pluck but it removed the column name from the output. I need the column name to be included as well. The $product table i refer(Referred in my code below) is just a table with product stuffs like name, price, discount rate etc..

Brief description

Present API response sample -

{
   "data" : [
      "Graham",
      "Marina Philip",
      "David Doomer",
           ],
   "message" : "",
   "success" : true
}

Expected response -

[
  {
    "name": "Graham",
  },
  {
    "name": "Marina Philip",
  },  {
    "name": "David Doomer",
  },

]

API Route from the APIController :

Route::resource('searchlist', 'API\SearchlistAPIController');

Index function from my SearchlistAPIController.php [Specific function]

           public function index(Request $request)
            {
                try{
                    $this->productRepository->pushCriteria(new RequestCriteria($request));
                    $this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
                    $this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
                    if($request->get('trending',null) == 'week'){
                        $this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
                    }
                    else{
                        $this->productRepository->pushCriteria(new NearCriteria($request));
                    }

                    $products = $this->productRepository->all();
        
                } catch (RepositoryException $e) {
                    return $this->sendError($e->getMessage());
                }
    //Here i've got the value of the table $Product with a bunch of columns from my database..
        
                $sendinger = $products->pluck('name');    
 
   //I'm trying to filter the columns send here. But i lost the column name as well.            
                
               return $this->sendResponse($sendinger->toArray(),'');
            }

Also, how can i remove this from my Json response ? :

 "message" : "",
   "success" : true


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire