Jrey21**'s avatar

Return empty object when I retrieve a data from server using 'remember_token' column

Why I'm getting an empty object as response from server every time I used this code User::where('remember_token', $token)?

Here's my User.php model

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'lastname', 'email', 'password', 'remember_token'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token'
    ];

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tbl_user';

    /**
     * User field validation
     */
    public $rules = [
        'firstname' => 'required',
        'lastname' => 'required',
        'email' => 'required|email|unique:tbl_user,email',
        'password' => 'required|min:6',
    ];

    /**
     * Check and get if email already exist.
     */
    public function findEmail($email) {
        return $this->where('email', $email)->firstOrFail();
    }

    /**
     * Update token of the user
     */
    public function refreshToken() {
        $this->remember_token = base64_encode(str_random(100));

        return $this->save();
    }

    /**
     * Delete token of the user
     */
    public function removeToken($token) {
        $information = $this->where('remember_token', $token)->firstOrFail();

        return $information;
    }

    /**
     * Lists of users
     */
    public function lists() {
        return $this->all();
    }

    /**
     * Create a new account
     */
    public function add($account) {
        return $this->create([
            'firstname' => $account->firstname,
            'lastname' => $account->lastname,
            'email' => $account->email,
            'password' => app('hash')->make($account->password)
        ]);
    }

}

All is working as expected, but whenever I use the User::where('remember_token', $token) or $this->where('remember_token', $token)->firstOrFail(); it returns an empty object, the data from database has a token and that token I use to pass to get the data using 'where' and a parameter of 'remember_token'

0 likes
1 reply
Jrey21**'s avatar
Jrey21**
OP
Best Answer
Level 1

This issue was solved by using self instead of $this keyword to target the User model.

Please or to participate in this conversation.