Create Your First Laravel User

Create Your First Laravel User

This is a quick tip to get that first user created in your application so you can log in and start testing things out.

You just installed a new Laravel application, configured the database, and ran migrations.

php artisan migrate

Now you go to your site and realize you don’t have a user to log in with yet. So your first thought is to just create a user manually in the database itself. However, the password column is used to store a hashed password. It should never store a plaintext password. If you attempt to put a plaintext password in the database, you still aren’t able to log in because Laravel is trying to compare the password you entered on the login screen to a hashed value.

So, how can we fix this?

The easiest way I’ve found is to use Tinker. Tinker is an extremely helpful REPL for Laravel that comes out of the box. To run it, just use Artisan:

php artisan tinker

Once in Tinker, we can use the User model just like in our application to create a user.

User::create([
 'name' => 'Sean',
 'email' => 'sean@example.com',
 'password' => Hash::make('password')
]);

Below is the sample output of doing just this:

Psy Shell v0.11.20 (PHP 8.2.8 — cli) by Justin Hileman
> $user = User::create(['name' => 'Sean', 'email' => 'sean@example.com', 'password' => Hash::make('password')]);
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
= App\Models\User {#6288
    name: "Sean",
    email: "sean@example.com",
    #password: "$2y$10$PjLdDohJMjtm2M08RBcgWOhvxZnAN1L1eMyCE2/G4ye7V9Ua9qeWS",
    updated_at: "2023-08-13 18:06:19",
    created_at: "2023-08-13 18:06:19",
    id: 1,
  }
>

The most important part of this is the password. We do not want to store it as plaintext and if we do, it won't work. So we need to hash the password using Laravel’s Hash facade:

Hash::make('password');

When using a starter set like Laravel Breeze, login is handled for you automatically. However, if you ever need to check a password against the hash, you can use the following:

Hash::check('password', $hashedPassword); // returns true or false

To read more about hashing passwords in Laravel, take a look at the documentation.

You can even customize the types of hashes that facade will create by adjusting the number of rounds the algorithm uses or switch the algorithm altogether from bcrypt to Argon2.

Did you find this article valuable?

Support Sean Kegel by becoming a sponsor. Any amount is appreciated!