2024 Full-Stack CRUD App using Vue.JS and Laravel 11 API with Authentication – Part 1

Posted by


Welcome to our Vue.JS full-stack CRUD app with Laravel 11 API with Authentication course! In this two-part tutorial series, you’ll learn how to create a fully functioning CRUD (Create, Read, Update, Delete) application using Vue.js for the frontend and Laravel for the backend.

In this first part, we will focus on setting up the Laravel API with Authentication. In the next part, we will build the Vue.js frontend to interact with the API.

Let’s get started!

Step 1: Setting up Laravel API with Authentication

  1. Install Laravel:
    First, ensure you have Composer installed on your system. Then, open a terminal and run the following command to create a new Laravel project:

    composer create-project --prefer-dist laravel/laravel project-name
  2. Database Configuration:
    Next, configure your database settings in the .env file. Set the DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD variables.

  3. Run Migrations:
    Run the following command to create the necessary tables in your database:

    php artisan migrate
  4. Install Passport:
    Laravel Passport is used for API authentication. Run the following command to install Passport:

    composer require laravel/passport
    php artisan passport:install
  5. Register Passport Middleware:
    Register Passport’s middleware in the AppHttpKernel.php file:

    'api' => [
       LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
       'throttle:api',
       IlluminateRoutingMiddlewareSubstituteBindings::class,
    ],
  6. Update User Model:
    In your AppModelsUser.php file, add the HasApiTokens trait:

    use LaravelPassportHasApiTokens;
  7. Update Auth Config:
    Set the driver option to passport in config/auth.php:

    'guards' => [
       'api' => [
           'driver' => 'passport',
           'provider' => 'users',
       ],
    ],
  8. Set up Authentication Routes:
    In your routes/api.php file, define the authentication routes for login, register, and logout:

    Route::post('login', 'AppHttpControllersAuthController@login');
    Route::post('register', 'AppHttpControllersAuthController@register');
    Route::middleware('auth:api')->post('logout', 'AppHttpControllersAuthController@logout');
  9. Create AuthController:
    Create a new controller AuthController using Artisan:

    php artisan make:controller AuthController
  10. Implement Authentication Methods:
    In your AuthController.php, implement the login, register, and logout methods using Laravel’s Authentication and Passport:

    use IlluminateSupportFacadesAuth;
    use AppModelsUser;
    
    public function login(Request $request)
    {
        $credentials = request(['email', 'password']);
    
        if (!Auth::attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
    
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
    
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => $tokenResult->token->expires_at,
        ]);
    }
    
    public function register(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);
    
        $validatedData['password'] = Hash::make($validatedData['password']);
    
        $user = User::create($validatedData);
    
        $tokenResult = $user->createToken('Personal Access Token');
    
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => $tokenResult->token->expires_at,
        ]);
    }
    
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
    
        return response()->json([
            'message' => 'Successfully logged out',
        ]);
    }

Congratulations! You have successfully set up the Laravel API with Authentication for our Vue.JS full-stack CRUD app. In the next part, we will cover building the Vue.js frontend to interact with this API. Stay tuned for Part 2!

In the meantime, feel free to explore more Laravel and Vue.js features and functionalities to enhance your skills further. Happy coding!

0 0 votes
Article Rating

Leave a Reply

15 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@tarik9563
1 hour ago

I am on a quasar project. I have no main.js file, where to put pinia use router like in your case ?

@zohaibahmed523
1 hour ago

Thank you so much! You're truly amazing in the way you explain everything. I was looking for a tutorial like this for so long, and I can't express how much I appreciate your effort. Hats off to you! Your guidance is incredibly clear and helpful. you're a true expert!

@khalidtubail
1 hour ago

I like the group of vs code extensions you have, can you send me the list of them, so I can use them, thanks and appreciated.

@khalidtubail
1 hour ago

i mean NuxtJs

@khalidtubail
1 hour ago

Amazing….., Hope you do a video to use Laravel API app with NuxJs

@wonderfulplanet-ts9hv
1 hour ago

thank for your video this is awesome and very helpful

@rosemaninedal3341
1 hour ago

will this kind of authentication will work, if I have a multiple vue app? and if I log-in thru vue-app1, then I switch to vue-app2, will I stay authenticated? can they share tokens?

@rajkumar_ravichandiran
1 hour ago

Hi Bro, Thanks for the tutorial. really helpfull, but I've small doubt.
exposing users token in localstorage is proper method ? anyone can see that token. will that lead to any xss attack?

@joshdevofficial
1 hour ago

everything are verywell explained. If you guys get confuse, you may use laravel vue inertia instead.

@stephen.cabreros
1 hour ago

nice nice , exactly what I need , thank you

@m_code_house
1 hour ago

I install vue js but router folder not exist in src folder but in your project it already created when you install?

@juanete2402
1 hour ago

Thank you for the video!! I have a question…. what is the difference between reactive and ref in vue?? thankss

@rashidmehmood5068
1 hour ago

Thank You

@heyykenn9099
1 hour ago

Laravel reverb next please

@nelsonke6840
1 hour ago

I like the way you explain concepts very well.After this can you please do a node and express crash course ? 🥹🥹

15
0
Would love your thoughts, please comment.x
()
x