I need to create an API with laravel and PHP.
I've created api routes to GET
all users and GET
all devices related to the user.
I've made the following tables in mySQL:
Devices:
increments('id');
string('name');
longText('description');
Table for relations between users and devices:
increments('id');
unsignedInteger('user_id');
unsignedInteger('device_id');
foreign('user_id')->references('id')->on('users');
foreign('device_id')->references('id')->on('devices');
Variables:
increments('id');
string('type');
unsignedInteger('device_id');
longText('description');
foreign('device_id')->references('id')->on('devices');
And the models have the relationscode:
User Model:
public function deviceVariables() {
return $this->hasMany('App\DeviceVariable');
}
public function devices()
{
return $this->belongsToMany('App\Device');
}
Device Model:
public function users()
{
return $this->belongsToMany('App\User');
}
public function variables()
{
return $this->hasMany('App\DeviceVariable');
}
And finally the DeviceVariable Model:
public function device()
{
return $this->belongsTo('App\Device');
}
public function user()
{
return $this->belongsTo('App\User');
}
I am able to show all the devices related to an authenticated user, but i am unable to show all the variables related to the devices that are related to that user.
This code (index method of DeviceVariablecontroller
) is the closest i've come to getting the variables:
$counter = 1;
$arrayIndex = 0;
while($counter <= 10) {
if(auth()->user()->devices()->find($counter)) {
$variables[$arrayIndex] = auth()->user()->devices()->find($counter)->variables;
$arrayIndex++;
}
$counter++;
}
Is there a way to make an array of all the user's devices' IDs and the loop through them?- or is there a smarter way to get all the variables of all the user's devices?
EDIT: Comment got me both the devices aswell as the each device variables.
$variables = auth()->user()->devices()->with('variables')->get();
return response()->json([
'success' => true,
'data' => $variables
]);
How can i get the variables ONLY without the device info?