Home > front end >  find() and delete() not working in laravel 9
find() and delete() not working in laravel 9

Time:10-28

find() This is correct:

$user = Users::where('userid', '=', $id)->get();
        return redirect('/register/view');

This is Incorrect:

$user = Users::find($id);
        return redirect('/register/view');

delete() This is Correct:

$user = Users::where('userid', '=', $id)->get();
        if(!is_null($user))
        {
            Users::where('userid', '=', $id)->delete();
        }
        return redirect('/register/view');

This is Incorrect:

$user = Users::where('userid', '=', $id)->get();
        if(!is_null($user))
        {
            $user->delete();
        }
        return redirect('/register/view');

Users Modedl:

class Users extends Model
{
    use HasFactory;
    protected $table = 'users';
    protected $primarykey = 'userid';
}

Both codes are correct but not in my case. i don't know why. can anyone tell me what is wrong.

CodePudding user response:

If you're looking for a single record by id (or userid in your case), don't use ->get():

$user = User::where('userid', $id)->first();
// OR
$user = User::find($id);

When deleting, also don't use ->get(). is_null on the result of ->get() will always be false, since ->get() returns a Collection, which isn't null.

$user = User::where('userid', $id)->delete();
// OR
$user = User::findOrFail($id)->delete();

Note: Your Model should be User, and the property to set the primary key in the Database is primaryKey, not primarykey:

class User extends Model {
  use HasFactory;
  protected $table = 'users';
  protected $primaryKey = 'userid';
}

You're misunderstanding and misusing Laravel a lot here. ->get() should never be used for a single record, model names are singular, casing matters, etc etc.

  • Related