0
votes

I am currently working on the creation of an API using Lumen. I have, for the example, 2 tables users and users_token with the corresponding models User and UsersToken.

The table users_token has 2 importants fields: user_id (foreign key linked with id field from users table) and token (a simple string).

In my model User, I have the method tokens that return all the tokens from the user using the hasMany() function:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function tokens()
    {
        return $this->hasMany('App\UsersToken');
    }
}

The table users_token also contains the defaults fields created_at and updated_at. So to get the oldest modified token of an user, I decide to use the oldest() function of Laravel:

$latestUserToken = $user->tokens->oldest('updated_at');

But sadly I get this error message:

Method Illuminate\Database\Eloquent\Collection::oldest does not exist.

Have someone an idea where my error is?

1

1 Answers

1
votes

Because $user->tokens return the Eloquent Collection.

oldest is a method of Eloquent-Builder and Query-Builder.

You need to call oldest method like this one:

$latestUserToken = $user->tokens()->oldest('updated_at')->first();

Laravel order by updated_at asc.