Get the updated value in laravel + vuejs - laravel

I have a edit page : http://localhost/smp/post/12
API ROUTE:
Route::get('package', [ProductController::class, 'update']);
In ProductController.php
public function update(Request $request) {
dd($request); //
}
In product.vue
axios
.post("/promotion-platform/api/images/upload",{ 'id' : this.id })
.then((res) => {
console.log(res.data);
})
eg: I fix the name box from 'Iphone 13' to 'Iphone 12'. And when I press update then I want to get the unique value I just modified.

on update method, you can return updated data.
On the vue side when you received success res.data you can over right it to do old data, then Vue's reactivity will update.
You can share also data of the component

Related

On Form Submit Inertia is not redirecting to particular page

I'm using Inertia (Vue3 & Laravel 9). I have a form in "Register.vue" Component.
On submitting that form I'm calling a controller to process the request. Once the controller process the request I want the controller to redirect to an other component i.e. regComplete (where I want to show data which I received as a prop from controller).
Now the thing is the Controller is redirecting me to the desired page (Although I'm unable to get the prop data but I'm getting the other data successfully) but the URL is still same as it was on form submit.
"Register.vue"
<template>
<form #submit.prevent="submit">Here are the form fields i.e. email & password </form>
</template>
<script setup>
let form = reactive({
email: "",
password: "",
});
let submit = () =>{
Inertia.post('users',form);
}
</script>
Route.php
//Route on submitting the form
Route::post('users',[userController::class,'register']);
Controller = userController
public function register(Request $request){
// $email = $request->input('email');
// $password = $request->input('password');
// return "User with".$email." and with password ".$password." is created";
return Inertia::render('regComplete');}
Now my question is How to redirect to the settings page with desired props ?
for example return Inertia::render('regComplete',['msg'=>'User registerd']);
After successfully creating a new user, you return the Component rather than returning or redirecting to another route where the component (regComplete) is being loaded.
What you can do is add more routes that deal with the (regComplete) component.
On routes.php, add the new route /registration/complete
Route::post('users',[UserController::class,'register']);
Route::get('/registration/complete',[UserController::class,'regComplete']);
On UserController.php, add new function regComplete() and update register
// add the this function
public function regComplete () {
return Inertia::render('regComplete',[
'users' => User::all() // make sure you have defineProps()
]);
}
// update your register function
public function register(Request $request){
// creation of user process here
if(successfully created) {
return redirect('/registration/complete');
}
return back()->with('error','You error message here');
}
It is possible that it will not solve your problem. However, hopefully it will assist you in determining where the problem may be occurring.

Axios gives undefined while accessing data at Vue's componenet in Laravel

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()
]);
}

How do I pass a variable from blade file to controller in laravel?

I have ProjectController that fetches data from the database and passes it to a blade file. One of the data items is the project_id. I want to pass the project _id from the blade file to another controller BidController.
ProjectController.php
public function show($id)
{
$project = Project::find($id);
return view('project.show',['project'=>$project]);
}
show.blade.php
div class="card-header">PROJECT <p>{!! $project->id !!}</p></div>
BidController.php
public function store(Request $request)
{
$bid = new Bid;
$bid->project_id = $project_id;
dd($project_id);
}
The dd(); does not output the project_id. I need help in passing the project_id from the blade file to the BidController method.
You can't directly set a model's id like you're doing in the line $bid->id = $project_id;. Are you trying to set up a relationship? That should be more like $bid->project_id = $request->project_id;.
Blade templates can't really pass things back to controllers, once they're in the browser your app is sort-of finished running. You need to create an HTML link/request on the page (like a form post request) that'll request the next thing from your app when the user clicks it.
If you want to create a button that creates a new bid for an existing project, you could do something like set up a form with a hidden field of 'project_id' that posts back to '/bids' which goes to the route 'bids.store'. You'll find 'project_id' under $request->project-id'.
You can send an AJAX request from Javascript:
View
<script type="text/javascript">
var project_id= {!! json_encode($project->id) !!}
$.ajax({
type: 'POST',
url: url, //Your bidController route
data: {project_id: project_id},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
},
success: function()
{
console.log('successful')
}
});
</script>
This will sent the data to the controller asynchronously so the user experience doesn't get affected.
One extra point: In your Bid controller, as project_id is coming from the request, you'll have to use:
$bid->id = $request->project_id;
I hope it helps!
PS: I'm using JQuery for this, so you'll have to include it if you don't already have.
I think this will solve your problem :
ProjectController.php
public function show($id)
{
$project = Project::findOrFail($id);
return view('project.show',compact('project');
}
web.php
Route::post('/bids/store/{id}' , 'BidController#store')->name('bids.store');
show.blade.php
div class="card-header">PROJECT <p>{{$project->id}}</p></div>
<form action="{{route('bids.store', $project->id)}}" method="post">
BidController.php
public function store(Request $request, $id)
{
$bid = new Bid;
$bid->id = $id;
$bid->save();
dd($id);
}

PUT errors in Vue

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');

How to send PUT request with a file and an array of data in Laravel

I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.
Please see the code below :
web.php ( route )
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController#update');
});
My angularjs product service :
function update(productId, data, onSuccess, onError){
var formData = new FormData();
formData.append('imageFile', data.imageFile);
formData.append('image', data.image);
formData.append('name', data.name);
formData.append('category_id', data.category_id);
formData.append('price', data.price);
formData.append('discount', data.discount);
Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined, {'Content-Type': undefined}).then(function(response) {
onSuccess(response);
}, function(response){
onError(response);
}
);
}
My ProductController update function
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
This is what I see in Chrome inspectmen
Please share your experiences on this problem. Thanks.
what you need is Only normal POST request with new field named _method=put then your code will work normally:
You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
Try this method:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
Also, make sure you're using Route::put or Route::resource for your route.

Resources