I have an application with Laravel and Vue. Controller has a method similar to this index
public function index(Request $request)
{
$people = Person::all();
if ($request->ajax()){
return response()->json($people);
}
return view('people.index')->withPeople($people);
}
The problem is: What´it is the right way to get data in front (Vue)?
We can use similar to this code
<example-component@prop('people', $people)></example-component>
Passing variables in components or we can use Axios.
CodePudding user response:
I could do something like the following
$people = Person::all();
if ($request->ajax()){
return response()->json($people);
}
Using Axios
getAll() {
return axios.get(`${base_url}/persons`);
}
Get all the persons
getPersons() {
return persons
.getAll()
.then(response => {
// console.log(this.persons);
this.persons = response.data;
})
.catch(error => {
console.log(error);
})
.finally(() => (this.loading = false));
},
In component
<example-component>{{persons}}</example-component>
CodePudding user response:
You can echo php variable inside script tag
In *.blade.php
<script>
var people = {{ $people }};
</script>
In vue script
const people = people; // or const people = window.people || ''
new Vue {
data() {
return { people }
}
}
In vue template
<example-component@prop('people', people)></example-component>