I can't make use of url with arguments in laravel

I am working with a rest API, and I cannot do the following query, it throws me an empty array and not the answer that I want to see:

 http://localhost/project-test/public/api/contactos/buscar?name=eric&surname=almendras

controller:

 public function buscar($name,$surname){
    $contacto = Contacto::where('name', $name,'surname',$surname)->get();
    return $contacto;
}

route: (api.php)

Route::get('contactos/buscar/{name}/{surname}','ContactosController@buscar');

Upvotes: 0

Views: 56

Answers (3)

Daniel
Daniel

Reputation: 2777

You define name and surname as url params, but you include it in query string. To access it you need to use Request class:

 public function buscar(Request $request){

    $name = $request->input('name');
    $surname = $request->input('surname');

    $contacto = Contacto::where([
       'name' => $name,
       'surname' => $surname
    ])->get();

    return $contacto;
}

or change url to:

http://localhost/project-test/public/api/contactos/buscar/eric/almendras

Upvotes: 2

Tony
Tony

Reputation: 10327

As Daniel says you need to get the parameters from the Request, you then have different options when querying the model.

You can put multiple where clauses in an array, as long as you want all the operators to be =, passed to a single where:

$contacto = Contacto::where([
    'name' => $name,
    'surname' => $surname
])->get();

or an array of arrays if you want to use different operators:

$contacto = Contacto::where([
    ['name', '=', $name],
    ['surname', '<>', $surname]
])->get();

or use multiple where functions

$contacto = Contacto::where('name', $name)
                    ->where('surname', $surname)
                    ->get();

or use Laravel's magic methods:

$contacto = Contacto::whereName($name)
                    ->whereSurname($surname)
                    ->get();

Upvotes: 0

Gert B.
Gert B.

Reputation: 2362

You need to put the 2 conditions in a separate where statement:

 $contacto = Contacto::where('name', $name)->where('surname',$surname)->get();

Upvotes: 1

Related Questions