veroneseComS
veroneseComS

Reputation: 768

Using WHERE in Laravel Returns Empty Array

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'
    ];  

}

Upvotes: 2

Views: 4524

Answers (4)

Saurabh Bhatewara
Saurabh Bhatewara

Reputation: 110

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

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

Upvotes: 2

wamba kevin
wamba kevin

Reputation: 309

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);
}

Upvotes: 4

Eric Vautier
Eric Vautier

Reputation: 148

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

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

Upvotes: 0

Abdo Abo
Abdo Abo

Reputation: 93

Change :

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

to

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

Upvotes: 0

Related Questions