Often I used Laravel API for my backend project. I work with front end developers using React to generate model data through an API. I chose Laravel because its secured and adaptable to many enpoints and comes with security and authentication.. This is going to be a fresh install of Laravel 10.

This article includes step 1 to install Laravel with users, Step 2 (link below) will add user authentication with tokens for SPA ready!

1. Create a Laravel Project:

$ laravel new [APP-NAME]

| |                             | |
| | __ _ _ __ __ ___ _____| |
| | / _` | '__/ _` \ \ / / _ \ |
| |___| (_| | | | (_| |\ V / __/ |
|______\__,_|_| \__,_| \_/ \___|_|

Creating a "laravel/laravel" project at "./noprem-laravel"
Installing laravel/laravel (v10.2.9)

2. Cd into the new app

$ cd [APP-NAME]

Add Sanctum, Resoures:

  1. https://www.webune.com/forums/laravel-with-login.sh.html
  2. https://www.webappfix.com/post/laravel-9-sanctum-api-authentication-tutorial.html
  3. https://laravel.com/docs/10.x/sanctum#how-it-works
  • $ composer require laravel/sanctum
  • $ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  • OPTIONAL: ADD EMAIL VERIFICATION: Click Here For Steps
  • $ php artisan migrate
  • $ code .
  • $ code README.md
  • $ code app/Http/Kernel.php
  • open app/Http/Kernel.php and uncomment middleware in 'api' section:  
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
  • $ git init
  • $ code .gitignore - > and Add README.me to make your notes.
  • $ git add .
  • $ git commit -m "initial"

Make a list of all the user form fields you will be needing: For example:

  1. First Name [fname]
  2. Last Name [lname]
  3. Email [email]
  4. Phone [phone]
  5. Address [address1]
  6. City [city]
  7. ...

View a list of all available Helpers: https://laravel.com/docs/10.x/helpers

 

Factories: Use this if you need to generate alot of fake users. If you need just one, go to the next step: Seeders For Factories, See below for more details

$ code database/factories/UserFactory.php

Example:

    public function definition(): array
    {
        return [
            'fname' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     */
    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }

 

 

Seeders - You can use the factory you created in the previous step to generate fake users, open DatabaseSeeder.php and uncomment the factory or you can create individual entries. Add the fields you need for a new user creation.

$ code database/seeders/DatabaseSeeder.php

Example:

    public function run(): void
    {
        // \App\Models\User::factory(10)->create();

        \App\Models\User::factory()->create([
            'fname' => 'John',
            'lname' => 'Smith',
            'email' => '[email protected]',
            'phone' => '2135551212',
            'password' => 'test123',
            'company' => 'ACME, Inc.',
            'address1' => '123 Main Street',
            'address2' => 'Apt #34',
            'city' => 'Any City',
            'state' => 'CA',
            'zip' => '90005',
            'country' => 'US',
            'level' => 1
        ]);
    }

 

 

Models - Open the Models/User.php file to add the fields

$ code Models/User.php

Resource:

  1. $fillable: What is $fillable & $guarded: https://www.youtube.com/watch?v=k2bS-RTU3Jg
  2. $hidden: Eloquent Model $hidden Property https://www.youtube.com/watch?v=4ou0WRXg3EY
  3. $casts: Laravel Custom Cast with Brick Money Package: https://www.youtube.com/watch?v=VViQBqC8Dbc

Example:

    protected $fillable = [
        'fname',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

 

 

Migrations database schema definition -

$ code database/migrations/*_create_users_table.php

Column Types: https://laravel.com/docs/10.x/migrations#available-column-types

Example:

        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('fname');
            $table->string('lname');
            $table->string('email')->unique();
            $table->string('company')->nullable();;
            $table->string('phone')->nullable();;
            $table->string('address1');
            $table->string('address2')->nullable();;
            $table->string('city');
            $table->string('state');
            $table->string('zip');
            $table->string('country');
            $table->boolean('active')->default(0);
            $table->integer('level')->default(1);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
 

 

Create Datatabse to connect and update .evn file:

$ code .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=noprem_laravel
DB_USERNAME=root
DB_PASSWORD=

 

Build Database

$ php artisan migrate:refresh --seed

Resource: https://www.webune.com/forums/laravel-database-migration-notes-sheetcheat-migrate-explanation.html

 

Start the server

$ php artisan serve

You can use postman to test API endpoints:

Factories- More info

Factories allow you to generate fake users, however many you want

$ code database/factories/UserFactory.php

Reference: https://laravel.com/docs/10.x/eloquent-factories#generating-factories
UserFactory has alread been created in database/factories/UserFactory.php by default.

You can add one fake user or use the Factory, for example:

 

Optional: Email Verification:

https://laravel.com/docs/10.x/verification

Next Step: https://www.webune.com/forums/laravel-add-user-authentication-api-for-backend-login-logout-register.html