2

I'm trying to do a WHERE in Laravel. My model has id_usuario, and in my database, I have five rows with id_usuario = 3, but Laravel is only returning an empty array.

Controller

<?php

public function show(Request $request)
{
    $animaisPerdidos = AnimalPerdido::where('id_usuario', $request->id);

    return response()->json($animaisPerdidos);
}

Route

Route::get('selectanimalperdido', 'AnimalPerdidoController@show');

In Postman

enter image description here

Model

class AnimalPerdido extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $table = 'animais_perdidos';

    protected $fillable = [
        'id', 'id_usuario', 'lat', 'lng', 'id_tipo_pet', 'raca', 'id_sexo', 'data', 'possui_identificador', 'id_cores', 'informacoes_adicionais', 'nome_identificador', 'foto'
    ];  

}

4 Answers 4

4

use the code below for your controller "get() if you want an array or first() if you want first result":

public function show(Request $request)
{
    $animaisPerdidos = AnimalPerdido::where('id_usuario', $request->id)->get();

    return response()->json($animaisPerdidos);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct - ->where(...) returns just a query builder, to actually get the results from query builder you need to call ->where(...)->get(), which will actually retrieve the results using the built query. Also, I don't think that $request->id is going to get you the input variable, as Eric pointed out and you should replace thast with $request->get('id') or $request->input('id').
2

Just append "->get()" at the end of query, like below:

AnimalPerdido::where('id_usuario', $request->id)->get();

Comments

0

Change :

Route::get('selectanimalperdido', 'AnimalPerdidoController@show

to

Route::get('selectanimalperdido/{id}', 'AnimalPerdidoController@show');

1 Comment

If he does that, he needs to change the controller as well, to receive the ID variable, as well as change the request url. But that's not needed here.
0

You need $request->input('id');

https://laravel.com/docs/5.7/requests#accessing-the-request

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.