I am trying to add conditional (ternary) operator in the blade to Laravel like:
<select name="staff" id="staff" class="form-control placeholder>
<option value="0">{{ __('messages.Select Staff') }}</option>
@if($staff != "Empty Staff")
@foreach ($staff as $item)
<option value="{{ $item->id}}" {{$item->stafftime->states == 'open' ? 'disabled' : ''}}>{{$item->name}}</option>
@endforeach
@else
<option value='0'> __('messages.Empty Staff')</option>
@endif
</select>
in my model staff and stafftime like blow:
protected $table = "stafftimes";
protected $fillable = [
'id', 'starttime', 'endtime', 'states', 'staff_id', 'created_at', 'updated_at'
];
protected $hidden = []; // Hide The Variable from select
public function staff()
{
return $this->belongsTo('App\Models\Staff', 'staff_id', 'id');
}
and in my staff model like:
protected $table = "staffs";
protected $fillable = [
'id', 'name', 'mobile'
];
protected $hidden = []; // Hide The Variable from select
public $timestamps = false;
public function stafftime()
{
return $this->hasMany('App\Models\Stafftime', 'staff_id', 'id');
}
I have an error
Property [states] does not exist on this collection instance
You are accessing a Collection that could potentially contain many Model instances when you access the dynamic property stafftime
on a Staff
model. If you want to know if any of those StaffTime
instances has the attribute 'states' set to 'open' you could use the contains
method of the Collection class:
$item->stafftime->toBase()->contains('states', 'open')
This would give you a boolean to use for your ternary condition.
The reason toBase()
is called there is because an Eloquent Collection (which the realtionship uses) overrides the contains
method to have different functionality, so we want to convert the Eloquent Collection to a regular Collection to be able to use the normal contains
functionality.
Laravel 8.x Docs - Collections - Available Methods - contains
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.