Dom
Dom

Reputation: 3444

Laravel API : how to get only some fields and sort the response

I would like to know if I do the things correctly.

Let's say I have a table "countries". To get only some fields of this table, in a certain order, I have this url :

/countries?fields=id,country_name&desc=country_name

And the result is clear:

[
    {
        "id": "SP",
        "country_name": "Spain"
    },
    {
        "id": "IT",
        "country_name": "Italy"
    },
    {
        "id": "FR",
        "country_name": "France"
    },
    {
        "id": "CN",
        "country_name": "China"
    } ]

To do that I have this route :

Route::get('/countries', 'CountryController@index');

And the method index is :

public function index(Request $request)
{
   
    $query = Country::query();
   
    if ($request->has('fields')){         
        $fields = explode(',', $request->input('fields') );          
        foreach ($fields as $field) {
            $query->addSelect($field);
        }        
    }
    
    if ($request->has('sort')){
        $query->orderBy($request->input('sort'));
    }
    
    if ($request->has('desc')){
        $query->orderBy($request->input('desc'), 'desc');
    }
   
    $countries = $query->get();
    
    return response()->json($countries, 200);
}

It works fine.

My question is am I doing the things correctly ? Is there any other methods ?

Upvotes: 0

Views: 1640

Answers (3)

Hussein
Hussein

Reputation: 1153

To prevent unknown column exception try this:

  1. import Schema class use Illuminate\Support\Facades\Schema;
  2. add this:

    $table = "countries";
    if ($request->has('fields')){
        $fields = explode(',', $request->input('fields') );
        foreach ($fields as $field) {
            if(!Schema::hasColumn($table,$field)){
                return response("Unknown field", 422);
            }
            $query->addSelect($field);
        }
    }
    

Upvotes: 2

Avinash Singh Rathi
Avinash Singh Rathi

Reputation: 115

You can try using this:

$countries = $query->pluck('id', 'country_name');

Please check and let me know.

Upvotes: 0

MaleihMaxime
MaleihMaxime

Reputation: 63

What you are doing to me has no vulnerability in it and is very optimized too.

Upvotes: 0

Related Questions