I'm using Laravel and Vue's component, and when i try to access the banners property from response returned by axios in vue component it gives me undefined.
I am accessing the perperty like response.data.banners
I'm returning data from controller in following way:
public function getBanners(Request $request){
return response()->json(['
banners'=> BannerImage::active()->get()
]);
}
Here is how i am accessing axios response
<script>
export default {
data: function() {
return {
banners: []
}
},
mounted() {
axios.get("getBanners").then((res)=> {
console.log(res);
console.log(res.data);
console.log(res.data.banners);
this.banners = res.data.banners;
});
console.log('Component mounted.')
}
}
</script>
Response by axios
All is working before accessing the banners property. Is there anything i am not doing correct ?
You have an linebreak ↩ between ' and banners, which is shown in the console line 2 "↩ banners":
Problem
public function getBanners(Request $request){
return response()->json([' // <-- ↩ line break
banners'=> BannerImage::active()->get()
]);
}
Correct
public function getBanners(Request $request) {
return response()->json([
'banners' => BannerImage::active()->get()
]);
}
Related
With Laravel 9/Inertiajs 3 I have page under adminarea with checking that user is logged as admin:
My vuejs page is container vue file and I read data using axios(that gives me possibility to run filter without all page reloading) :
axios.post(route('admin.currencies.filter'), filters)
.then(({data}) => {
currencyRows.value = data.data
})
.catch(e => {
showRTE(e) // custom error
console.error(e)
})
and :
<?php
class CurrencyController extends Controller
{
public function index()
{
if ( ! auth()->user()->can(ACCESS_APP_ADMIN_LABEL)) {
return redirect(route('admin.dashboard.index'))
->with( 'flash', 'You have no access to currencies listing page')
->with('flash_type', 'error');
}
return Inertia::render('Admins/Currencies/Index', []);
}
public function filter()
{
\Log::info( varDump(-9, ' -9 filter::') );
if ( ! auth()->user()->can(ACCESS_APP_ADMIN_LABEL)) {
\Log::info( varDump(-98, ' -98 INSIDE filter::') );
return redirect(route('admin.dashboard.index'))
->with( 'flash', 'You have no access to currencies filter method')
->with('flash_type', 'error');
}
...
$currencies = Currency
::getByName($filter_name)
->orderBy($order_by, $order_direction)
->paginate($backend_items_per_page, array('*'), 'page', $page);
return (CurrencyResource::collection($currencies)); // collection of resources
} // public function filter()
...
php>
The problem is that when in filter method invalid access code is run(I check it in file) app is not redirecred to dasboard page, but is run next
and I got javascript error as filter method did not return valid data which are expected on client...
Looks like redirect can not be run from axios code... How that can be done?
Thanks!
You may change axios to this.$inertia : [https://inertiajs.com/manual-visits]
this.$inertia.post(this.route('...'),{},{
only:['...']
});
My code looks like this
child component.vue
<script>
export default {
props: ['Pconvs_id'],
data(){
return{
user : '',
messages:[],
newMessage : '',
convs_id: '',
}
},
created(){
this.convs_id = this.Pconvs_id;
this.fetchMessages();
},
methods:
{
fetchMessages()
{
console.log(this.convs_id);
axios.get('messages',{cons_id: this.convs_id}).then(response=> {
this.messages = response.data;
});
axios.get('authuser').then(response=>{
this.user = response.data;
});
},
},
watch: {
// whenever convs_id changes, this function will run
Pconvs_id: function (newConvs_id, oldConvs_id) {
this.convs_id = newConvs_id;
this.fetchMessages();
}},}
</script>
parent component.vue
<Message :Pconvs_id="convs_id"/>
my problem is that even when the convs_id changed fetchmessage() return same data what did i do wrong
axios call handler
public function fetchmessages(Request $cons_id)
{
return Message::where([
['cons_id' , $cons_id],
])->with('user')->get();
}
Elequent relationship
message model beongsTo user and User hasMany message
I think your backend handler receives an instance of Illuminate\Http\Request
so to get the cons_ids you should to something like
public function fetchmessages(Request $request)
{
// Get the cons_id from the request object
$cons_id = $request->get('cons_id');
// Cleaned up your "where" query
return Message::where('cons_id', $cons_id)->with('user')->get();
}
Sometimes I need to pass data from my controller to the view and sometimes I dont!
But when theres no data passed I get this error:
Undefined variable: tutorial (View:
/var/www/html/resources/views/home.blade.php)
No data example:
public function index()
{
return view('home');
}
Containg data example
public function tutorial()
{
return view('home', ['tutorial' => 'Welcome to myproject, lets get started!!!']);
}
Blade:
beforeMount()
{
let tutorial = {{ var_export($tutorial) }} // ERROR!!
if (tutorial) {
return
}
this.reloadData()
}
I think I can do this way in my index function:
public function index()
{
return view('home', ['tutorial' => []);
}
But its just gross!! Theres anyway to check if data passed from laravel exists in my vue??
Because you cannot just put the Laravel variable in js.
Options to solving the problem included:
Performing an api request for the data using the application
component once it had been mounted.
Attaching the data into the
Javascript context using the blade template.
You can do some thing like this:
<Home tutorial="{{ $tutorial }}"> <!-- make tutorial become to props -->
</Home>
And in your view component:
Vue.component('Home', {
props: [
{
name: 'tutorial', // add this props
default: '',
}
],
beforeMount()
{
if (this.tutorial) { // use like this.tutorial
return
}
this.reloadData()
}
});
I'm trying to update data using laravel. I'm not sure why I can't access the PUT api. I tied so switch the api to store the data vs update and that works. I can't see anything wrong with the code.
Here is the api router
Route::put('product', 'ProductController#update');
here is the controller
public function update(Request $request, $id)
{
$product= Product::findOrFail($id);
$product->update($request->all());
return ['message' => "Success"];
}
Here is the vue.js
methods: {
updateProduct(id){
this.$Progress.start();
this.form.put('api/product/'+this.form.id)
.then(() => {
// success
$('#addNew').modal('hide');
Swal.fire(
'Updated!',
'Information has been updated.',
'success'
)
this.$Progress.finish();
Fire.$emit('AfterCreated');
})
.catch(() => {
this.$Progress.fail();
});
},
In the Vue component I have a modal with a form
<form #submit.prevent ="editmode ? updateProduct() : createProduct()">
The error I'm getting is
405 (Method Not Allowed)
The error I was getting was in the api router.
Route::put('product/{id}', 'ProductController#update');
I'm trying to set axios request but always getting missing argument, but not sure how can I pass it can someone explain why this wont work?
my route: (web.php)
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
my controller: (Controllers/API/SessionsController.php)
class SessionsController extends Controller
{
public static function setSuccessMessage($key, $value)
{
session()->put($key ,$value);
}...
and my vueJS axios call (resources/assets/components/Login.vue)
created: function () {
// check is user logged out
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'}).then((response)=> {
console.log(response);
})
},
Use :
public static function setSuccessMessage(Request $request)
{
$key = $request->get('message');
$value = $request->get('message2');
session()->put($key ,$value);
}
If you want to send the data as a part of your request body you can do so like
axios.post('/api/setSuccessMessages', {message: 'message',message2: 'message2'})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage/{message}/{message2}', 'API\SessionsController#setSuccessMessage');
If you wish to send the data as a request params (everything after ? in the url) you can do so like this
var params = {
message1: message1,
message2: message2
};
axios.post('/api/setSuccessMessages', {}, {'params': params})
.then((response)=> {
console.log(response);
}
)
//you then accept them as such
Route::post('/api/setSuccessMessage', 'API\SessionsController#setSuccessMessage');
//You can further use them as such in controller
function public test(Request $request) {
$request->get('message1');
$request->get('message2');
}
I'll reference axios official docs for the axios request params