未定义的属性:App\Ticket::$status laravel 7



Ticket.php

public function getStatusAttribute()
{
if ( $this->status == 0 ) {
return ['label' => 'closed', 'bs_class' => 'badge badge-secondary'];
}
if ( $this->status == 1 ) {
return ['label' => 'answered', 'bs_class' => 'badge badge-success'];
}
return ['label' => 'waiting', 'bs_class' => 'badge badge-warning'];
}

ticket.blade.php

<td>
@php $status = $ticket->status @endphp
<span class="{{ $status['bs_class'] }}">
{{ $status['label'] }}
</span>
</td>

迁移

public function up()
{
Schema::create('tickets', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('diaphragmUnit');
$table->tinyInteger('status')->default(0);
$table->text('message');
$table->timestamps();
});
}

我想显示车票状态的label

但上面写着:

未定义的属性:App\Ticket::$status

编辑

控制器

public function index()
{
$tickets = Ticket::latest()->paginate(25);
return view('Admin.tickets.index', compact('tickets'));
}

您需要在访问器中提供一个参数:

public function getStatusAttribute($status)
{
if ( $status == 0 ) {
return ['label' => 'closed', 'bs_class' => 'badge badge-secondary'];
}
if ( $status == 1 ) {
return ['label' => 'answered', 'bs_class' => 'badge badge-success'];
}
return ['label' => 'waiting', 'bs_class' => 'badge badge-warning'];
}

因此,您还将把$this->status更改为简单的$status

这不是精确的测试解决方案它只是为了提供一些想法您可能需要修复一些错误,ps:这不是准确的解决方案,也没有经过测试,所以请不要判断它是

public function getStatusAttribute()
{
if ( $this->status == 0 ) {
$status = array('label' => 'closed', 
'bs_class' => 'badge badge-secondary'
);

}
else if ( $this->status == 1 ) {
$status = array('label' => 'answered', 
'bs_class' => 'badge badge-success'
);

}
else 
{
$status = array( 'label' => 'waiting',
'bs_class' => 'badge badge-warning'
);
}

return view('yourViewname', ['status' => $status] );
}

在您的视图中

<td>   
<span class="{{ $status['bs_class'] }}">
{{ $status['label'] }}
</span>
</td>

getStatusAttribute方法中,您必须从$attributes属性访问状态

public function getStatusAttribute()
{
$status = $this->attributes['status'] ?? null;
if ( $status == 0 ) {
return ['label' => 'closed', 'bs_class' => 'badge badge-secondary'];
}
if ( $status == 1 ) {
return ['label' => 'answered', 'bs_class' => 'badge badge-success'];
}
return ['label' => 'waiting', 'bs_class' => 'badge badge-warning'];
}

错误与迁移文件无关。它实际上来自于您尝试访问的地方

$ticket->状态

在您的ticket.blade.php中。原因是因为在您的服务getStatusAttribute中,响应数据没有"门票";属性,而您的返回值应该是

public function getStatusAttributeService()
{
if ( $this->status == 0 ) {
$status = ['status'=> ['label' => 'closed', 'bs_class' => 'badge badge-secondary']];
}
if ( $this->status == 1 ) {
$status = ['status'=>['label' => 'answered', 'bs_class' => 'badge badge-success']];
}
$status = ['status'=> ['label' => 'waiting', 'bs_class' => 'badge badge-warning']];
return view('callYourViewHere',['ticket'=>$status]);
}

最新更新