How to use Laravel's API resources for efficient data shaping in vue js



Image not found!!

Laravel's API resources are a powerful tool for transforming your Eloquent models and model collections into a properly formatted JSON response. When combined with Vue.js on the frontend, you can efficiently shape and display data in your application.

Here's a step-by-step guide on how to use Laravel's API resources with Vue.js:

1. Create API Resource

Create a new API resource using the artisan command:

bash
php artisan make:resource PostResource

This will generate a new resource file in the app/Http/Resources directory.

2. Define Transformation in the Resource

In the newly created resource file (PostResource in this case), you can define how your data should be transformed. For example:

php
// app/Http/Resources/PostResource.php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class PostResource extends JsonResource { public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'body' => $this->body, 'created_at' => $this->created_at->toDateTimeString(), 'user' => new UserResource($this->whenLoaded('user')), ]; } }

In this example, UserResource is another API resource that represents the user associated with the post.

3. Use the Resource in the Controller

In your controller, use the resource to shape the data before sending it as a response:

php
// app/Http/Controllers/PostController.php use App\Http\Resources\PostResource; public function index() { $posts = Post::with('user')->get(); return PostResource::collection($posts); }

4. Fetch Data in Vue.js

Use a tool like Axios to make a request to your Laravel backend and fetch the data in your Vue.js component:

javascript
// Your Vue.js component <template> <div> <div v-for="post in posts" :key="post.id"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> <p>Created by: {{ post.user.name }}</p> </div> </div> </template> <script> export default { data() { return { posts: [], }; }, mounted() { this.fetchPosts(); }, methods: { async fetchPosts() { try { const response = await axios.get('/api/posts'); this.posts = response.data.data; } catch (error) { console.error('Error fetching posts:', error); } }, }, }; </script>

5. Display Data in Vue.js Component

Now, your data is shaped and ready to be used in your Vue.js component. The PostResource ensures that the data sent from Laravel is in the desired format, making it easier to work with in your frontend.

Remember to adjust the code according to your specific use case, and consider adding pagination if you have a large dataset. Laravel provides pagination support, and you can handle it on the Vue.js side as well.