在Laravel中使用WHERE返回空数组

问题描述 投票:0回答:4

我正试图在Laravel做一个WHERE。我的模型有id_usuario,,在我的数据库中,我有五行id_usuario = 3,但Laravel只返回一个空数组。

调节器

<?php

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

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

路线

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

在邮递员

enter image description here

模型

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

}
php laravel eloquent
4个回答
0
投票

只需在查询结尾附加“ - > get()”,如下所示:

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

2
投票

如果你想要一个数组,请使用下面的代码为“get()”,如果你想要第一个结果,则使用first():

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

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

0
投票

变化:

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

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

0
投票

你需要$ request-> input('id');

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

© www.soinside.com 2019 - 2024. All rights reserved.