Why put request is not working using axios to make a laravel api request? - laravel

Here is a request from my Vue component:
submit() {
axios
.put(`/api/posts/${this.slug}`, this.fields, {
headers: { "content-type": "multipart/form-data" },
})
.then((res) => {
// some logic
})
.catch((error) => {
// some logic
});
}
api.php
Route::group(['prefix' => 'posts', 'middleware' => 'auth:sanctum'], function () {
Route::put('/{post:slug}', [PostController::class, 'update']);
});
put method doesn't work. I get the following error xhr.js:220 PUT http://127.0.0.1:8000/api/posts/test-title-updated-33 422 (Unprocessable Content) but when I replace put with post everything works as expected. I don't understand why put is not working.

Because HTTP PUT is not recognized by HTML standard.
You need to add POST type of method only but for update you can add a small flag with POST request for a PUT/PATCH type of operation.
axios.post(`/api/posts/${this.slug}`, { // <== use axios.post
data: this.fields,
_method: 'patch' // <== add this field
})

Related

Laravel Current User off of a Fetch Request

so I am trying to get the active user off of a fetch request to my backend.
My front end code is:
let apiToken: string | null = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('http://192.168.0.6:8000/api/testURL', {
method: "POST",
//#ts-ignore
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text-plain, */*',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': apiToken
},
credentials: 'same-origin',
body: JSON.stringify(data)
})
.then(function(response): void {
console.log(response);
})
.catch(function(err): void {
console.log(err);
});
I have a CSRF token in a meta tag that is generated from csrf_token();
My backend code is:
Route::post('/testURL', function(Request $request)
{
$status = $request->input('status');
$comment = $request->input('comment');
$prospectType = $request->input('prospectType');
$leadId = $request->input('leadId');
$requestUser = $request->user();
return response()->json([
'status' => $status,
'comment' => $comment,
'prospectType' => $prospectType,
'leadId' => $leadId,
'user' => $requestUser
]);
});
The end result from the API call back shows 'user' as null.
I have tried Auth::user() & Auth::id() and they all return null.
I am at a lose and tried using Sanctum to create a validation token which when I added an auth:sanctum middleware it returned a 302 to redirect.
(The same redirect is happening when I apply a vanilla "auth" to a non-Sanctum token'd request).
The request out of all of this!
I want to ensure I have user by ID validation when I send up the request from the frontend to the backend.
I figured it out, the reason the request was not working correctly was the sanctum.php config file did not have my local IP (what I am running my php artisan serve off of) in its 'stateful' array.
I hope this helps anyone! That was five hours of my life.

How to update data in Vue js and Laravel?

I'm trying to update my form. For some reason, it's working in Postman but not in the browser. I'm using axios to make requests and I have v-model's on all my form fields.
I've tried with both PUT and PATCH and I getting this error respectively:
The PATCH method is not supported for this route. Supported methods: GET, HEAD.
Here is my code for loading the data in the form and the Update function:
editProfile(profile) {
this.editProfileData = {...profile};
this.showEditProfileModal();
},
updateProfile: async function() {
axios.patch(this.uri + '/' + this.editProfileData.id, {
employment_type: this.editProfileData.employment_type,
date_of_birth: this.editProfileData.date_of_birth,
experience: this.editProfileData.experience,
skills: this.editProfileData.skills,
}).then(response=>{
this.hideEditProfileModal();
this.$toast.success(response.data.message);
})
.catch(error=>{
this.$toast.error(error.response.data.message);
});
},
Here are my routes api.php:
Route::group(['middleware' => 'auth:api'], function() {
Route::post('candidate/profile', function() {
return response()->json([
'message' => 'Candidate access',
'status_code' => 200
], 200);
})->middleware('scope:candidate');
Route::post('candidate/profile/create', function() {
return response()->json([
'message' => 'Candidate access',
'status_code' => 200
], 200);
})->middleware('scope:candidate');
// Route For Candidate Profile Pages
Route::resource('/candidate/profile', 'CandidateProfileController', ['names'=>[
'index'=>'candidate.profile.index',
'create'=>'candidate.profile.create',
'store'=>'candidate.profile.store',
'edit'=>'candidate.profile.edit',
'update'=>'candidate.profile.update'
]])->middleware('scope:candidate');
});

Laravel API call goes through even with session expired

I have a SPA based on Laravel 5.8 and Vue 2.0.
Everything is working fine, a little bit too much to be honest, because if I delete the session and I try to save the content afterward or keep navigating the private pages, every ajax call that I'm doing with Axios is going through without returning any error. Only if I forcefully refresh the page I get the error page I setup but if I don't, I can keep doing everything even if the session no longer exist.
This is my setup.
web.php is where I have the only php route that points to a singlePageController:
Auth::routes();
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
Then in the singlePageController I return the view:
class SinglePageController extends Controller
{
public function index() {
return view('app', ['loggedUser' => auth()->user()]);
}
}
Then I have the api.php where I have the API routes. As you can see at the end I have the middleware to make it private. Just to make an example this is the one I use for updating the content:
Route::put('event/update/{slug}', 'EventController#update')->middleware('auth:api');
Then the related controller of that API route:
public function update(Request $request, $slug)
{
$event = Event::where('slug', $slug)->first();
$event->title = $request->input('title');
return new EventResource($event);
}
And in the end this is the Resource I use to define what and how the API data is going to be displayed:
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'curator' => $this->curator,
'featured_image' => $this->featured_image,
'body' => $this->body,
'date' => $this->date
];
}
So this above is the flow I have. Then when I do an axios call to update the content, I'm doing something like:
axios({
method: 'PUT',
url: '/api/event/update/' + this.$route.params.slug + '?api_token=' + this.isLogged.apiToken,
data: dataToSave,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
.then((response) => {
this.getNotification('Success: The Event has been saved');
})
.catch((error) => {
this.getNotification('Error: Impossible saving the event');
console.log(error);
})
Thanks in advance for the help
In Laravel routes in api.php ignore the session data.
If you want to authenticate with session data you could move your api routes to web.php and you should see the results you expect.

Laravel Spark 6.0 Ajax request unauthenticated

I am building an app from a vanilla Spark 6.0 installation. I can login, access the Kiosk and click around.
I have created a new Card section with a form and am using the SparkForm object as directed by the documentation; however every single request returns unauthenticated and thus I have to re-login.
I cannot get the ajax request to authenticate. I have created a seperate adminApi to handle admin ajax request which is protected by auth/dev/web middleware.
Any ideas/pointer much appreitated.
Relevent Code:
RouteServiceProvider:
public function map(Router $router)
{
$this->mapWebRoutes($router);
$this->mapApiRoutes($router);
$this->mapAdminApiRoutes($router);
//
}
...
protected function mapAdminApiRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace,
'middleware' => ['dev', 'auth', 'web'],
'prefix' => 'admin/api',
], function ($router) {
require base_path('routes/adminApi.php');
});
}
routes/adminApi.php
Route::resource('/insurers', 'Admin\InsurersController');
vue component - insurers.js
var base = require('kiosk/users');
Vue.component('spark-kiosk-insurers', {
mixins: [base],
data: function() {
return {
showingInsurerProfile: false,
form: new SparkForm({
name: '',
email:'',
logo:''
})
}
},
props: {
insurer: {}
},
methods: {
search: function() {
},
create: function() {
Spark.post('/admin/api/insurers', this.form)
.then(response => {
console.log(response);
});
},
}
});
Add the CSRF Token to the form like
<meta name="csrf-token" content="{{ csrf_token() }}">
Then add the following to your request:
headers: {
'X-CSRF-TOKEN': 'Token Here' // from meta
}

Vue request fails but does not log errors

I have this add method in my vue script
if (this.edit === false) {
this.link.link = submitEvent.target.elements.link.value;
fetch('products', {
method: 'POST',
body: JSON.stringify(this.link),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(res => { // this does not get executed
this.qrcode.redirect_url = "";
alert('Added');
this.fetchAll()
})
.catch(err => console.log(err.res));
}
}
When I fill the form the request is send and entry is made to the database but I do not get response.
I am using laravel as backend and Add method in Controller returns 200 response after creation.
What could cause it and why console.log(err) does not not display anything?

Resources