Laravel fetchi API Data + vue - laravel

Getting to know Laravel a bit more and I was wondering what's the best way to pass my data from my controller into my Vue component?
I have understood how to actually pass it as a prop, however, I can't seem to get it to render the way I want. my props in my Vue component are. My controller here:
{
public function fetch() {
$data = Http::get('https://jsonplaceholder.typicode.com/albums')->json();
return view('welcome', ['data' => $data]);
}
}
My view then passes on the data to my vue component like this.
<example-component :albums="#json($data)" />
My Vue props structure is below.
props: {
albums: {
type: Array,
default: []
},
}
Heres how im trying to render the data in my vue component:
<div>
<h1 v-for="album in albums" :key="album.id">
{{ album.title }}
</h1>
</div>
</template>
Results here enter link description here
I have verified the output from my controller is an array containing arrays. Am I handling the data wrong from the perspective of my Vue component?

you dont need to convert it to json :albums="#json($data)" it's already json ->json();
try replace
:albums="#json($data)"
with this
:albums="{{ $data }}"

Related

how to access data ($count) from laravel controller to vue component

I want to access a variable $count from my controller and access it to a vue component (frontend). currently have this code on my controller:
public function index()
{
$count = User::where('created_at', Carbon::today())->count();
return view('user.index', compact('count'));
}
i am quite new to laravel and vuejs so please help me out. thank you!
Send count as a prop from blade to component
<your-component-name :count="{{ $count }}"></your-component-name>
And from your component, receive that prop
<template>
<div>
Count is {{ count }}
</div>
</template>
<script>
export default {
props: {
count: {
type: Number
}
}
}
</script>
To pass down data to your components you can use props. Find more info
about props over here. This is also a good source for defining those
props.
You can do something like:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example v-bind:userId="{{ Auth::user()->id }}"></example>
And then in your Example.vue file you have to define your prop. Then
you can access it by this.userId.
Like :
<script>
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
</script>
the above question was answered in below question
Pass data from blade to vue component

How to pass an object from Laravel to Vue without using props

I'm setting up some Vue Components in my Laravel 5.8 application, that require user information available through Auth::user(), most importantly, the api_token that I must use in my axios requests. I want to pass the Auth::user() object from Laravel to Vue in a secure and private method.
I initially passed the object as props, but I don't want private information on the object to be easily exposed using browser extensions such as Vue DevTools. Now, I've been searching for a way to define global variables inside the Blade Template and access them in Vue:
Pass data from blade to vue component
https://forum.vuejs.org/t/accessing-global-variables-from-single-file-vue-component/638
https://zaengle.com/blog/layers-of-a-laravel-vue-application
Based on those links above, it seems like what I need to do is set the variables to the window object, but I'm unsure on what I'm doing something wrong to achieve this. When I define the variable in the Blade Template, I can see the variable is assigning properly by doing console.log() but the problem comes when I try to use it in Vue.
app.blade.php
#if(Auth::user())
<script>
window.User = {!! json_encode(Auth::user()) !!}
console.log(window.User)
</script>
#endif
component.vue
<script>
export default {
data: function() {
return {
user: window.User
}
}
}
</script>
I've tried setting the data as window.User, this.User, and simply just User but it always comes up as undefined. What am I missing? Or is there any other/better way to do this?
Try the following Vue Component:
<template></template>
<script>
export default {
data: function() {
return {
user: window.User
}
},
created(){
console.log(this.user)
},
}
</script>
I could see the user data from the console.log in Vue component.

How to pass a Laravel filtered collection as array to Vue?

I have a component which I'm trying to make it receive an array.
If I do it like this in a blade file:
<mega-menu :grouped-categories="{{ $categories->toJson() }}"></mega-menu>
It works as intended. It appears in Vue as array.
However, if I try to run some collection methods like 'filter' and 'groupBy' and then apply 'toJson', Vue receives it as an Object which is not what I need.
<mega-menu
:grouped-categories="{{ $categories->filter(function($category) { return $category['enabled']; })->groupBy('group)->toJson() }}">
</mega-menu>
I'm suspicious that something is happening during filtering or grouping that converts it into an array. Any ideas on how to manipulate ´$categories´ variable which is an instance of Collection and make it pass as array to Vue?
According to the information provided by #Vivick, the associative arrays pass to Javascript as Objects. So I'll handle the Object inside the Vue component.
To avoid problems with special chars add addslashes in template like:
:users="'{{ addslashes(\App\Users::all()->toJson()) }}'"
In vue component get the Users as prop:
props: {
users: String
},
And add it to data
data() {
return {
users: JSON.parse(this.mailinglists)
};
},
Hope this helps.
use
v-bind:color="{{json_encode($yourVariable)}}"
in element
for example:
<color-item v-bind:color="{{json_encode($yourVariable)}}" ></color-item>
in your controller:
$myArray = array("name" => "لوازمات");
$item = "لوازمات";
$collection = Color::all();
return view('home', compact('item', 'collection', 'myArray', ...));
in your blade:
#extends('layouts.app', ['item' => $item,'myArray' => $myArray, 'colors'=> $collection])
pass variable into vuejs:
<primary-header
:colors="{{json_encode($colors)}}"
:item="{{json_encode($item)}}"
v-bind:my-array="{{json_encode($myArray)}}">
in your vuejs file
<template>
<div>
{{item}}
{{colors[0].name}}
{{myArray.name}}
</div>
</template>
<script>
export default {
name: "primary-header",
props: {
item: String,
myArray: Object,
colors: Array
},
methods: {
}
};
</script>
<style scoped>
</style>

Laravel + Bootstrap-Vue Table not accepting data

I'm currently playing with Laravel Spark and I'm slowly learning the Vue.js system.
I have a bunch of data I want to display in a table that is pulled from AWS DynamoDB. I am successfully parsing this data in sorts of ways and can display the data in a standard static Bootstrap table. I'm now trying to use the Vue.js version and I cannot for the life of me get this data to display at all. If I insert dummy data into the Vue Component, the dummy data shows so it must be the way I'm passing the data in.
My code as follows:
TableController.php
public function show()
{
$data = $this->fetchAWSData($condition); // This is my separate AWS method
return view('table')->with('items', $data);
}
table.blade.php
#extends('spark::layouts.app')
#section('content')
<home :user="user" inline-template>
<div class="container-fluid" style="text-align: left">
<h1>Data</h1>
<MyTable items={{ $items }}></MyTable>
</div>
</home>
#endsection
MyTable.vue
<template>
<b-table striped hover :items=items></b-table>
</template>
<script>
export default {
data() {
return {
items: this.items
}
}
}
</script>
What am I doing wrong here? I've tried formatting my data all sorts of ways; JSON, manually, Arrays... nothing works. So it must be the way I'm passing it in.
Any insight would be AMAZING :)
You have to use props to be able to pass attributes to Vue's components.
MyTable.vue
...
<script>
export default {
props: ['items'],
}
</script>
Then you can pass data to component:
<MyTable :items="{{ $items }}">

Pass data from blade to vue component

I'm trying to learn vue and with that I want to integrate it with laravel too..
I simply want to send the user id from blade to vue component so I can perform a put request there.
Let's say I have this in blade:
<example></example>
How can I send Auth::user()->id into this component and use it.
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
To pass down data to your components you can use props. Find more info about props over here. This is also a good source for defining those props.
You can do something like:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example v-bind:userId="{{ Auth::user()->id }}"></example>
And then in your Example.vue file you have to define your prop. Then you can access it by this.userId.
Like :
<script>
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
</script>
If you are serving files through Laravel
Then here is the trick that you can apply.
In Your app.blade.php
#if(auth()->check())
<script>
window.User = {!! auth()->user() !!}
</script>
#endif
Now you can access User Object which available globally
Hope this helps.
Calling component,
<example :user-id="{{ Auth::user()->id }}"></example>
In component,
<script>
export default {
props: ['userId'],
mounted () {
console.log(userId)
}
}
</script>
Note - When adding value to prop userId you need to use user-id instead of using camel case.
https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function. By default, the #json directive calls the json_encode function with the JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_AMP, and JSON_HEX_QUOT flags:
<script>
var app = #json($array);
var app = #json($array, JSON_PRETTY_PRINT);
</script>
Just to add for those who still get error.
For me this <askquestionmodal :product="{{ $item->title }}"></askquestionmodal> still gives error in console and instead showing html page I saw white screen.
[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
Coupling to connect 2 rods М14 CF-10
Raw expression: :product="Coupling to connect 2 rods М14 CF-10"
Though in error I can see that $item->title is replaced with its value.
So then I tried to do like that <askquestionmodal :product="'{{ $item->title }}'"></askquestionmodal>
And I have fully working code.
/components/askquestionmodal.vue
<template>
<div class="modal-body">
<p>{{ product }}</p>
</div>
</template>
<script>
export default {
name: "AskQuestionModal",
props: ['product'],
mounted() {
console.log('AskQuestionModal component mounted.')
}
}
</script>

Resources