【问题标题】:getting database toArray not work in laravel获取数据库 toArray 在 laravel 中不起作用
【发布时间】:2020-10-01 15:07:25
【问题描述】:

当我从数据库中获取数据时

$agent = DetailUser::get();

情况正在好转。 但是当我回来时

$agent = DetailUser::get()->toArray(); 

它说找不到和错误 404。 为什么会这样?

这是我的迁移

        Schema::create('detail_user', function (Blueprint $table) {
        $table->bigIncrements('id_detail_user');
        $table->unsignedBigInteger('id_user');
        $table->string('nama');
        $table->string('institusi');
        $table->bigInteger('telepon');
        $table->bigInteger('saldo')->default(0);
        $table->string('foto')->nullable();
        $table->timestamps();
        $table->foreign('id_user')->references('id_user')->on('users')->onDelete('cascade');
    });

这是我的模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DetailUser extends Model
{
protected $primaryKey='id_detail_user';
protected $table = 'detail_user';
protected $fillable = ['nama','institusi','foto','telepon','saldo'];
protected $appends = ['image_URL'];

public function getImageURLAttribute()
{
    if ($this->foto == null) {
        abort(404);
    }
    return asset('uploads/peserta/' . $this->foto);
}
public function users(){
    return $this->belongsTo(User::class,'id_user');
}

}

【问题讨论】:

  • 你能分享你的路由和控制器吗?
  • 我的工作正常。问题不在这里,在您提到的代码上
  • 我的也是。我认为这与查询无关。
  • 我已经更新了模型和迁移,我的控制器就像第一个代码一样尝试从数据库中获取数据

标签: laravel eloquent


【解决方案1】:

您正在将该 Collection 序列化为一个数组,这会导致每个模型都调用访问器getImageURLAttribute;您已将此附加到序列化输出中。所以显然其中一个没有foto

你在那个方法中实际上是用 404 中止。

【讨论】:

  • 当用户没有照片时我应该怎么做才能替换中止(404)?
  • 什么都不要,或者使用一些默认图像
猜你喜欢
  • 2019-12-15
  • 1970-01-01
  • 2016-01-20
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 1970-01-01
  • 2022-06-28
  • 2017-06-23
相关资源
最近更新 更多