Cors laravel not review reactjs axios năm 2024

Aiming to master full-stack development? Pairing Laravel with Vue.js paves the path, particularly for authentication tasks.

Cors laravel not review reactjs axios năm 2024

In this guide, we’ll delve into how Laravel, Vue, and Laravel Sanctum can be merged to craft an API authentication in two distinct methods:

  1. Merging Laravel and Vue in a Single Page Application (SPA)
  2. Using Vue and API as individual projects

Let’s get started.

Setting Up a Laravel Single Page Application with Breeze and Vue

First things first, create a new Laravel project. Run this command:

composer require laravel/breeze --dev

Run the following commands one after the other:

php artisan breeze:install vue php artisan migrate npm install npm run dev

After this, you’ve got yourself a fully functional Single Page Application (SPA).

Head to

php artisan make:controller DemoController

6. Here, you'll find controllers that manage authentication. A noteworthy file is

php artisan make:controller DemoController

7, specifically the

php artisan make:controller DemoController

8 method:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

Let’s craft a “protected” demo component. This component will only be visible to logged-in users and will showcase the ID and name of the user currently logged in.

First, you need to create a new controller named

php artisan make:controller DemoController

9. Use the following command:

php artisan make:controller DemoController

Open up the

php artisan make:controller DemoController

9 you've just created under

public function index() { return Inertia::render('Demo/Index'); } }

1. Add the following content:

public function index() { return Inertia::render('Demo/Index'); } }

Add an appropriate route for this controller in your

public function index() { return Inertia::render('Demo/Index'); } }

2 file.

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

The component should be accessible only by authorized users. For that, place the route under the

public function index() { return Inertia::render('Demo/Index'); } }

3 middleware, alongside profile routes. Update the

public function index() { return Inertia::render('Demo/Index'); } }

2 like this:

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

Open

public function index() { return Inertia::render('Demo/Index'); } }

5 to add a link for your new demo route. After your dashboard link, add:

Demo  

Your menu should look something like this:

Navigation Links >

Inside

public function index() { return Inertia::render('Demo/Index'); } }

6, add:

Typically in Laravel, you’d access the logged-in user data with

public function index() { return Inertia::render('Demo/Index'); } }

7. But in the Vue-Inertia setup, we use

public function index() { return Inertia::render('Demo/Index'); } }

8. This function provides the session's shared data globally.

Peek into

public function index() { return Inertia::render('Demo/Index'); } }

9 and you'll notice new middlewares:

php artisan breeze:install vue php artisan migrate npm install npm run dev

0

The first one,

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

0, is intriguing. Delve into

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

1 and you'll see:

php artisan breeze:install vue php artisan migrate npm install npm run dev

1

This is where the data for the currently logged-in user is added, which matches the

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

2 line in our Vue component.

Using Laravel Sanctum for SPA Authentication

If you’re planning to synchronize data between your main application and third-party services using your API, you might want to consider setting up an API. The advantage here is having one central “truth source,” removing the hassle of updating data in multiple places.

Enter Laravel Sanctum. This is Laravel’s neat solution for authenticating Single Page Applications (SPAs) that need to liaise with a Laravel-backed API. With Sanctum, your SPA can authenticate in two ways:

  1. Stateful Authentication: Using cookies from the Laravel session if you’re already logged in.
  2. Stateless Authentication: Leveraging API tokens.

Now, let’s discuss a pre-existing endpoint that fetches authenticated user data. By default, this is bundled with your Laravel installation and can be found in the

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

3 file. A significant aspect to note is that this route is guarded by the

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

4 middleware.

Here’s a simplified look at the code:

php artisan breeze:install vue php artisan migrate npm install npm run dev

2

Let’s tweak the

public function index() { return Inertia::render('Demo/Index'); } }

6 component to fetch and display the user's details dynamically from the API. We need

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

6 and

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

7 from Vue, the layout, and the header functionalities.

php artisan breeze:install vue php artisan migrate npm install npm run dev

3

We’ll use a function,

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

8, that sends a request to our API endpoint (

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

  1. to get the user's data. Once the data is retrieved, we'll update our

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

0.

php artisan breeze:install vue php artisan migrate npm install npm run dev

4

Now, let’s use the fetched data in our template. We’ll showcase the user’s ID and name within our demo component:

php artisan breeze:install vue php artisan migrate npm install npm run dev

5

Heads-up: With this setup, when the component mounts, it will attempt to fetch user data from

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

9. However, if you're not authenticated, the request will face a hurdle - returning a

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

2 status. This indicates you need authentication before accessing the user's data. Always make sure to handle such cases in your application to ensure a seamless user experience.

Laravel Sanctum requires you to integrate a specific middleware to ensure seamless SPA-to-API communication. Add this middleware to the

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

3 middleware group located in your

public function index() { return Inertia::render('Demo/Index'); } }

9 file:

php artisan breeze:install vue php artisan migrate npm install npm run dev

6

Your SPA and API should ideally be on the same top-level domain, albeit on different subdomains. This is essential for seamless cookie-based authentication.

For Sanctum to work, it needs to recognize domains accessing it as “stateful”, meaning they can maintain a session. Set this up in your

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

5 file using the

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

6 variable.

Example: If both your SPA and API exist on the same domain, merely setting the

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

7 should suffice:

php artisan breeze:install vue php artisan migrate npm install npm run dev

7

Sanctum then aims to fetch the domain value from

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

7. However, if there's a mismatch between

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

7 and the actual browser URL, you'll need to explicitly set

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

6:

php artisan breeze:install vue php artisan migrate npm install npm run dev

8

Occasionally, developers use the

Demo  

1 command for quick local testing. This command serves your application at addresses like

Demo  

2. In such scenarios, the standard authentication setup might falter.

To remedy this, if you’re using a URL that has a port, ensure

use App\Http\Controllers\DemoController; // ... other routes ... Route::middleware('auth')->group(function () {

Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');  
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');  
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');  
Route::get('/demo', [DemoController::class, 'index'])->name('demo');  
});

6 includes the port:

php artisan breeze:install vue php artisan migrate npm install npm run dev

9

Setting Up Vue Client with Laravel API Using Sanctum Token Authentication

Sanctum offers the ability to generate API tokens, facilitating the authentication of API requests. This chapter will guide you in setting up a standalone front-end client to tap into an API that’s backed by Laravel.

While we can utilize the application we established in the previous chapter as our API server, you’re free to initiate a new Laravel project if you deem it necessary. To begin, ensure your User model incorporates the

Demo  

4 trait:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

0

For those working on newer projects, you probably already have the

Demo  

5 trait embedded. To dispense a token, employ the

Demo  

6 method. This hands you a

Demo  

7 object. To retrieve the token in plain text, resort to the

Demo  

8 attribute. Let's design a route to facilitate user logins. During login attempts, the system will authenticate the provided credentials. Post-validation, a new token will be produced and dispatched to the user. On unsuccessful attempts, an error message will be delivered.

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

1

Next, we need a route to cater to user logout requests. On invoking this route, the system will expunge the token used for authentication.

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

2

Take note that the

Demo  

9 endpoint is shielded with

Route::get('/demo', [DemoController::class, 'index'])->name('demo');

4 middleware, ensuring token deletion requests come exclusively from authenticated users.

Setting Up a Vue Client

In this guide, we’ll walk you through creating a Vue Single Page Application (SPA) that will interact with a separate Laravel API. The project setup will leverage Vite for its build system.

Ensure you’ve got the latest version of Node.js on your system.

To set up a new Vue project, open your command line and input:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

3

For our setup, we chose the following configurations:

  • Project Name: myproject
  • TypeScript: No
  • JSX Support: No
  • Vue Router (for SPA): Yes
  • Pinia (for state management): No
  • Vitest (for Unit Testing): No
  • End-to-End Testing Solution: No
  • ESLint (for code quality): No

Here, we specifically opted for Vue Router, a vital tool for SPA development:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

4

Once the project is initialized, you can install its dependencies and get the development server running:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

5

Upon successful startup, a message will confirm that your server is operational, providing you with a link to access your application:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

6

We’ll integrate Axios into your Vue project. Axios is a popular JavaScript library for making HTTP requests.To begin, let’s install Axios:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

7

Let’s make some adjustments to your main Vue application file (

Navigation Links >

  1. to integrate Axios.

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

8

  • We configure axios to recognize XHR requests and abide by CORS policies with the ‘X-Requested-With’ header.
  • We set the baseURL so you don’t have to specify the full path for every request, just the endpoint’s relative path.
  • We utilize localStorage to store and retrieve the user’s token. If the token exists, it’s set as the default Authorization header for Axios requests.
  • Axios interceptors act similarly to Laravel’s middleware. If a token is expired or invalid, the interceptor detects a Navigation Links > 2 response, removes the token, and redirects the user to the login page.

With the steps completed, your Vue project is now ready to interact seamlessly with your Laravel API. Adjust the

Navigation Links >

3 placeholder with your actual Laravel API server address.

We will walk you through the process of creating a login component in Vue that interacts with a Laravel API. To start, create a

Navigation Links >

4 component inside the

Navigation Links >

5 directory with the following structure:

Script Section:

public function store(LoginRequest $request): RedirectResponse {

$request->authenticate();  
$request->session()->regenerate();  
return redirect()->intended(RouteServiceProvider::HOME);  
}

9

Template Section:

php artisan make:controller DemoController

0

Style Section:

php artisan make:controller DemoController

1

  • Reactive State & Message: The Navigation Links > 6 object holds the email and password, and we've also defined a Navigation Links > 7 ref to display potential errors.
  • Submit Function: Upon form submission, the Navigation Links > 8 function is triggered. The function:
  • Clears any previous error message.
  • Posts the login data to the specified endpoint.
  • Upon successful login, the user’s token is saved locally and they’re redirected to the UserView.
  • If an error occurs (like invalid credentials), an error message will be displayed.
  • Once the request is processed, the password is cleared for security.
  • API Call: Given that we previously set the base URL in Navigation Links > 1, the 0 is effectively a call to 1. The form data gets passed as the second argument.

This component offers a simple, yet comprehensive way to manage login in a Vue application connected to a Laravel backend. Adjust

Navigation Links >

3 to your actual API server's address.

We’ll design a Vue component,

3, that showcases the logged-in user's details and allows the user to sign out.

Navigate to the

Navigation Links >

5 directory and craft a new file named

3 with the following content:

Script Section:

php artisan make:controller DemoController

2

Template Section:

php artisan make:controller DemoController

3

  • Loading User Data: As soon as 6 comes into view, the 7 function is automatically triggered thanks to the 8 lifecycle hook. This function fetches the user's data from the 9 route and updates the php artisan breeze:install vue php artisan migrate npm install npm run dev 00 object.
  • Sign Out Process: The php artisan breeze:install vue php artisan migrate npm install npm run dev 01 function:
  • Contacts the server to invalidate the current token.
  • Regardless of the server’s response, the function takes a safe approach by:
  • Deleting the stored token on the client-side.
  • Resetting the Axios authentication header.
  • Redirecting the user back to the login screen.

In the final step, we need to set up routing for our Vue application. This means defining clear paths to access our

php artisan breeze:install vue php artisan migrate npm install npm run dev

02 and

6 components. Here's a simplified guide to do that:

In your

php artisan breeze:install vue php artisan migrate npm install npm run dev

04 file, include the paths for

php artisan breeze:install vue php artisan migrate npm install npm run dev

02 and

6 like so:

php artisan make:controller DemoController

4

For a broader perspective, let’s see the complete route setup in

php artisan breeze:install vue php artisan migrate npm install npm run dev

04:

php artisan make:controller DemoController

5

  • The main routes of our Vue app are php artisan breeze:install vue php artisan migrate npm install npm run dev 08, php artisan breeze:install vue php artisan migrate npm install npm run dev 09, and php artisan breeze:install vue php artisan migrate npm install npm run dev 10.
  • The php artisan breeze:install vue php artisan migrate npm install npm run dev 11 route is an example of a lazy-loaded component, which means it's only loaded when visited, helping improve initial page load times.
  • The php artisan breeze:install vue php artisan migrate npm install npm run dev 12 and php artisan breeze:install vue php artisan migrate npm install npm run dev 13 functions from 'vue-router' facilitate the creation of the routing instance.

With these routes in place, you’re now ready to leverage Sanctum authentication to interface with the Laravel API. This setup is versatile, fitting both unified applications relying on cookie-based sessions, and split setups with distinct repositories for the API and frontend.

If you liked the article, show your support with a clap 👏 and follow me! Feel free to highlight your favorite parts too. Your engagement keeps me inspired!

Unlock the power of Domain-Driven Design in Laravel! Start mastering Data Handling, Services, CQRS, and more. Join those who’ve leveled up with our comprehensive eBook!