Update with Laravel does not take model id

Asked

Viewed 1,103 times

0

I am trying to perform a simple function to change the password of the logged in user using the code:

$user = User::find(\Auth::user()->idusuario);
$user->password = bcrypt($request['novasenha']);
$user->save();

But it doesn’t work. I noticed that the executed query does not take user id:

update USUARIOS set password = ? where IDUSUARIO is null

I realized that this problem of "where IDUSUARIO is null" also repeats in other situations. How should I do this? Because it does not take the id that is being passed?


<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    protected $table = "USUARIOS";
    protected $primaryKey = 'IDUSUARIO';
    public $timestamps = false;

    /**
     * The database table used by the model.
     *
     * @var string
     */

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'idusuario', 'nomerazao', 'email', 'cpfcnpj', 'telefone', 'idperfil', 'situacao', 'password'
    ];

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

    public function getAuthIdentifier()
    {
        // TODO: Implement getAuthIdentifier() method.
        return $this->attributes['idusuario'];
    }

    public function regras(){
        return $this->belongsToMany('App\Models\RegrasModel', 'REGRASUSUARIOS', 'IDUSUARIO', 'IDREGRA');
    }

}
  • 2

    Your update says to update the password of everyone who has it null, ie more than one user can be affected.

  • If I’m not mistaken Auth::user()will return an instance of User ai does not need the User::find(...), could stay Auth::user()->password = bcrypt($request['novasenha']). Put as this your Model User.

  • I’ve tried using it like this, and I got the same result.

4 answers

1

This is not an error. Actually, maybe the column name in the table or something else is wrong.

The problem is being caused because Auth::user()->idusuario is returning NULL.

For example, if you try to make a find, the consultation will stay like this:

 DB::enableQueryLog();
 DB::table('usuarios')->find(null);
 DB::getQueryLog ();

Upshot:

select * from usuarios Where id is null limit 1

Another thing: Whenever you use a framework try to use its conventions. Whether for database, or for anything else (name of methods and the like).

The widely used pattern in Laravel for Primary Keys is simply the id.

It is possible to change this, but remember to do it in a way that does not run too far from the standards of the Framework.

I noticed that you used the definition names of some attributes in Uppercase, and then so much access them with Lowercase. This is not a good idea!

Always keep a pattern to write your codes!

It is also important to remember that Laravel will use the method __get to access the value of attributes, which in turn are stored in the property Model::$attributes.

A test you can do to detect your error is to debug the values being stored in the model, thus:

 dd(Auth::user()->getAttributes());

You will notice that Laravel will not do the magic name conversion in Uppercase to Lowercase, for you to access them.

In your case, it’s not even necessary to make a find, since Auth::user() returns the Model instance used for the authentication component.

See how you can do:

 Auth::user()->update(['password' => bcrypt('senha')])
  • Thanks for the feedback, but the names in the attributes are not defined by me. They are already from the bank that the company uses here, so I used "IDUSUARIO" and since the bank is Oracle, it is not case sensitive in the name of the attributes (at least I never had problems). In relation to Auth::user()->idusuario it returns 37 which is the user id. I used your Auth::user()->update(['password' => bcrypt('password')]) method and it still didn’t work.

1

When doing this function, Voce already loads the user variable with the authenticated user.

$user = \Auth::user();
$user->password = bcrypt($request['novasenha']);
$user->save();

0

I make the words of @Wallace Maxters (referring a user was removed?) mine, but it seems to me that the main reason for the problem is the value you defined the "primaryKey" property within your template. It is set to uppercase letters, thus:

protected $primaryKey = 'IDUSUARIO';

Which results in a query with the column letters also uppercase, thus:

update USUARIOS set password = ? where IDUSUARIO is null

Try changing to lower case (or change to the exact value of your database) this way:

protected $primaryKey = 'idusuario';

Anyway, if your authentication system is working, try using the Auth knife to get the logged in user, this way:

$loggedInUser = \Auth::user();
$loggedInUser->setAttribute('password', '...');
$loggedInUser->save();

A simple test you may be performing is, the Auth facade has a method to get the authenticated user id, try using find with this value, so:

$loggedInUserId = \Auth::id();

$loggedInUser = User::find($loggedInUserId);
$loggedInUser->setAttribute('password', '...');
$loggedInUser->save();

I also believe that it is not necessary to add the "idusuario" column in your model’s "fillable" property.

0

I use in the Laravel 7 pulling directly

use App\User;
User::where('id', '=', Auth::id())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.