I got a User Class
class User extends Model implements
AuthenticatableContract,
CanResetPasswordContract,
AuthorizableContract,
MustVerifyEmailContract {
//use HasApiTokens, HasFactory, Notifiable, MustVerifyEmail;
use MustVerifyEmail, HasApiTokens,Authenticatable, Authorizable, CanResetPassword, Notifiable;
protected $table = 'users';
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'username',
'email',
'password'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
public function devices(){
if($this->is_admin){
return Device::query();
}
return $this->belongsToMany(Device::class);
}
public function testseries(){
$devices = $this->devices();
dd($devices->getRelation('testseries')->get()->toArray());
}
}
In my case, should I do $devices->get()
it gives me a empty collection.
Now I want to get the relation from devices to testseries. But i dont want to get an collection.
I want to call manually later somewhere $user->testseries()->get()
because maybe I want to modify something with where.
Is that possible?
Currently $devices->getRelation('testseries')->get()
returns an collection of all testseries while $devices->get()
give me an empty collection of devices. But I expect an empty collection too because there are no devices, so there shouldnt be any testseries for the user.
I dont want to use $devices->with('testseries')
because then I'll get a Collection of Device models with the relation. But I Want a collection of testseries instead.
Is there any way or workaround to get that?
I tried it with pluck, load and with. But nothing gives me my expected result and they are already loaded in a wrong collection format because I want a collection of testserie Model.
EDIT:
Here are all other Model classes:
class Testserie extends Model
{
use HasFactory;
/**
* @var string[]
*/
protected $fillable = [
'device_id',
'date',
];
public function measurements(): HasMany {
return $this->hasMany(Measurement::class);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function device(): \Illuminate\Database\Eloquent\Relations\BelongsTo {
return $this->belongsTo(Device::class);
}
}
class Device extends Model
{
use HasFactory;
/**
* @return BelongsToMany
*/
public function users(): BelongsToMany {
return $this->belongsToMany(User::class);
}
/**
* @return HasMany
*/
public function testseries(): HasMany {
return $this->hasMany(Testserie::class);
}
}