Laravel和mySQL与关系表

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?

Maybe something like this:

$variables = auth()->user()->devices()->with('variables')->get();

This will eager load relationships that devices had.

For accessing only users variables you can use has-many-throught relationship like mentioned in docs:

https://laravel.com/docs/5.7/eloquent-relationships#has-many-through

You can use a BelongsToMany relationship to get the variables directly:

public function variables()
{
    return $this->belongsToMany('App\DeviceVariable', 'device_user',
        null, 'device_id', null, 'device_id');
}

return response()->json([
    'success' => true,
    'data' => auth()->user()->variables
]);