How to send data from laravel controller to vue.js?

by hal.littel , in category: PHP Frameworks , 6 months ago

How to send data from laravel controller to vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months ago

@hal.littel 

To send data from a Laravel controller to a Vue.js component, you can use Laravel's Blade templating engine to pass the data to your Vue component as props. Here's a step-by-step guide to achieve this:

  1. In your Laravel controller, fetch the data that you want to pass to your Vue component. For example, let's say you have a controller method that retrieves a list of tasks:
1
2
3
4
5
6
public function index()
{
    $tasks = Task::all();
    
    return view('tasks.index', ['tasks' => $tasks]);
}


  1. In your Blade view file (e.g., resources/views/tasks/index.blade.php), you can pass the data to your Vue component as props by using the @json Blade directive to convert the data into a JSON representation:
1
<tasks-component :tasks="@json($tasks)"></tasks-component>


  1. In your Vue component, you can define the props property to receive the data passed from the controller:
1
2
3
4
5
6
7
export default {
    props: ['tasks'],
    
    mounted() {
        console.log(this.tasks);
    }
}


Now, when your Vue component is mounted, it will have access to the tasks data passed from the Laravel controller via props. You can then use this data in your Vue component as needed.


That's it! You have successfully sent data from a Laravel controller to a Vue.js component.