In this tutorial, we will explore the integration of Axios, Vue 3, and Laravel to facilitate a smooth data retrieval process through GET requests. This guide walks you through the steps to implement a Laravel 10 Vue 3 Axios Get Request example. The primary focus is on fetching data from a server using Axios within a Vue.js component in a Laravel web application.
Laravel 10 Vue 3 Axios Get Request Example
Step 1: Install Laravel 10
If you haven't created a Laravel app yet, you can initiate one using the following command:
composer create-project laravel/laravel example-app
Step 2: Create Controller
Generate an APIController.php
file with a getData()
method to handle the data retrieval:
// app/Http/Controllers/APIController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class APIController extends Controller
{
public function getData()
{
$data = ['message' => 'Hello, This is from Laravel API!'];
return response()->json($data);
}
}
Step 3: Create Route
Define a route in the api.php
file to invoke the APIController's getData()
method:
// routes/api.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\APIController;
Route::get('/data', [APIController::class, 'getData']);
Step 4: Install Laravel UI
Install Laravel UI and Vue scaffolding:
composer require laravel/ui
php artisan ui vue
npm install && npm run dev
Step 5: Update Vue Component
Modify the default ExampleComponent.vue
to include Axios for data fetching:
<!-- resources/js/components/ExampleComponent.vue -->
<template>
<!-- ... -->
<div class="card-body">
{{ message }}
</div>
<!-- ... -->
</template>
<script>
export default {
data() {
return {
message: '',
};
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
axios.get('/api/data')
.then(response => {
this.message = response.data.message;
})
.catch(error => {
console.error('Error fetching data:', error);
});
},
},
};
</script>
Step 6: Update Blade File
Adjust the welcome.blade.php
file to include the Vue component:
<!-- resources/views/welcome.blade.php -->
<!-- ... -->
<body>
<div id="app">
<example-component></example-component>
</div>
</body>
<!-- ... -->
Run Laravel App
Execute the following command to start your Laravel application:
php artisan serve
This Laravel Vue 3 Axios Get Request example demonstrates a streamlined approach to integrate Axios with Laravel and Vue.js for efficient data retrieval. By following these steps, you empower your web application to seamlessly communicate with the server and display the fetched data in Vue components. Happy coding!