Vue component
methods: {
removeCategory(index) {
if (confirm('Are you sure ?')) {
let id = this.categories[index].id;
console.log("ID="+id);
if (id > 0) {
axios.delete('/api/categories/' + id);
}
this.categories.splice(index, 1);
}
},
Routes Api
Route::delete('/categories/{category}', 'CategoryController#destroy');
Controller
public function destroy(Category $category)
{
$this->authorize('delete', $category);
$category->delete();
return $category;
}
Put request is working fine for inserting and updating data, but DELETE request is not able to delete data from the database.
Thanks
Laravel check CSRF token.
You need to add X-CSRF-TOKEN in the request header
You can read this doc : https://laravel.com/docs/7.x/csrf#csrf-x-csrf-token
If you haven't found the answer yet, quick fix as:
Remove the model binding in your Controller.
Grab specific category with an id.
Authorize and delete it.
(no need to modify the Component and the Route)
Related
In my app (Laravel + InertiaJS + Vue3), I want to refresh some client-side JS variables based on a client-side parameter:
Client has a table of events, each one holding a button with its corresponding event_id.
When pressed, the server receives a request and performs some calculations (dynamically generates an external URL and some parameters). Nothing is persisted to the database.
Hopefully, the generated URL and the parameters are sent-back to the client, and the user is then redirected there (client-side) using a POST form (that is why I can not redirect directly from the server).
What is the best way to do that?
This is what I have so far:
// In my controller
...
public function __construct()
{
$this->generator = new URLGenerator();
}
public function generate(Event $event)
{
$url = $this->generator->getURL($event);
return redirect()->back();
}
// My controller
public function index()
{
return Inertia::render('Events', [
'events' => fn () => new EventResource(
auth()->user()->events
)
]);
}
I need to somehow inject the $url variable back to Vue.
Thanks in advance for any help.
I am try to pass a from ionic application to a laravel 5.4 application, and this parameter is an array, i have been able to pass the parameter successfully but i am being able to use the parameter to select records from the database.
Here is my ionic 3 provider function:
getMySmartQueues(data){
let params = new HttpParams();
params = params.append("sq_ids", JSON.stringify(data));
return this.http.get(this.url + 'my/smart/queues', {params: params});
}
And here is my laravel controller function:
public function getMySmartQueues(Request $request){
$ids = $request['sq_ids'];
$my_sq = SmartQueue::whereIn('id', $ids)->get();
return $my_sq;
}
And here is how i subcribe to the provider function is my page:
ionViewDidLoad() {
this.storage.get('sq_ids').then(
res => {
console.log(res);
if(res != null){
this.sq_ids= res;
console.log(this.sq_ids);
this.mService.getMySmartQueues(this.sq_ids).subscribe(
data => {
console.log(data);
}
);
}
}
);
}
But i get Server internal error. But if i have to hard code a default value for the controller function, let say like [5,6], it will return the records of this ids, but it can not returns the records of the ids sent from the ionic 3 application, will be glad if any one can help me out.
Also if i change the request to a put request i can get the records of the ids sent from the ionic application. But a get request is what i want.
if you want to use controller function with GET you need allow arguments in the Route to allow your id array.
for an example.
Route::get('your/url/{ids}', 'Controller#function')->name('mane_of_the_route');
and the controller function
public function getMySmartQueues(array $ids){
$my_sq = SmartQueue::whereIn('id', $ids)->get();
return $my_sq;
}
I have figure it out, and this is what i had to do, i think it might help someone one day, i just had to json_decode the request like so:
public function getMySmartQueues(Request $request){
$ids = $request['sq_ids'];
$my_sq = SmartQueue::whereIn('id', json_decode($ids))
->with(
'station.company'
)->get();
return $my_sq;
}
I am little confused about session as i am new to in laravel. On my laravel app there is a lists of activity, every activity has it's details. When i click on activity button(button name: interesed?) activity id add on session, If i add another activity it is also add on session. I need functionality to add and remove inquiry id from session & on last i want all added activity id.
Note: I am doing using ajax.
What i have done sharing here.
Here is a view of my lists inquiry
On my web.php define a route
Route::get('addInquiryData','Front\PlanController#addInquiry')->name('addInquiryData');
On view view.blade define onclick function
onclick="addInquiry({{ $activity->id }})"
On my ajax call
function addInquiry(id) {
var activity_id = id;
if(activity_id)
{
$.ajax({
type:"GET",
url:"{{ route('addInquiryData') }}?activity_id="+activity_id,
success:function(res)
{
if(res)
{
// operation here
}
}
});
}
}
On my controller just define a function.
public function addInquiry(Request $request) {
dd($request->activity_id); // gt activity id here
}
How can i do this?
You may try this code
Store Your Activity Id value in variable
$activityId=$request->activity_id
You can add value in session like this
if(!Session::has('activity_'.$activityId)){
session(['activity_'.$activityId=>$activityId]);
}else{
session()->forget('activity_'.$activityId);
}
You can remove value in session like this
session()->forget('activity_'.$activityId);
I am trying to send a delete request via axios to laravel as follow:
axios.delete('api/users/' + this.checkedNames)
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
Now from axios documentation I read that for delete request we should be using a configObject so the above could be rewritten as so:
axios.delete('api/users/', {params: {ids:
this.checkedNames})
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
I have then Route::resource('users', 'UsersController'); in api.php so the default route for deleting is:
DELETE| api/users/{user}| users.destroy
and the controller's method is:
|App\Http\Controllers\UsersController#destroy
I am able to delete as expected a user when I pass a single id let's say api/users/12, it gets deleted correctly but when I try to pass the array above things get complicated.
if I try as per axios documentation axios.delete('api/users/', {params: {id: this.checkedNames}}) it looks I am sending this http://lorillacrud.dev/api/users?id[]=21&id[]=20 but I get a 405 method not allowed.
if I try axios.delete('api/users/' + this.checkedNames ) I get http://lorillacrud.dev/api/users/20,21 so in my destroy method I could grab the ids and delete, but I am wondering if this is the correct way to do it?
update
I seemed I made it work but I am not understanding so any help still appreciated to make a sense of what I am actually making work!
So, if change to:
axios.delete('api/users/destroy', {params: {'id': this.checkedNames})
and in my destroy method:
if ($request->id) {
foreach ($request->id as $id) {
User::destroy($id);
}
}
User::destroy($id);
}
So...
// not deletes the user
axios.delete('api/users/destroy', {params: {id: id}})
// ok deletes the users when using request->id in a for loop in the destroy laravel method.
axios.delete('api/users/destroy', {params: {ids: this.checkedNames}})
// ok deletes one user
axios.delete('api/users/' + id)
sorry guys but I have a lot of confusion why and what !!!
The route name is user.destroy why does it work when I pass an array and it does not when I pass a single value, why viceversa the route with method delete will not delete when pass an array ???
Any difference between using api/users/destroy vs api/users only?
Thanks for any help on this!
I also experienced the same problem. This works for me:
deletePost: function(id) {
axios.post('/posts/'+id,{_method: 'delete'})
}
Using axios.post() instead of axios.delete, and sending _method "delete"
It is because of the method signatures. The default delete route when using Resource expects a single parameter. So when doing:
axios.delete('api/users', {params: {'id': this.checkedNames})
you are missing a required parameter. The route definition is
Route::delete('api/users/{id}', 'UserController#destroy');
// You are missing `id` here. So it won't work.
Usually, if you are going to stray away from the default behavior, it is recommended to create your own function. So you could leave the default destroy($id) function as is to delete a single entry and write a new function that will delete many. Start by adding a route for it
Route::delete('api/users', 'UserController#deleteMany');
Then define the function to handle it
public function deleteMany(Request $request)
{
try
{
User::whereIn('id', $request->id)->delete(); // $request->id MUST be an array
return response()->json('users deleted');
}
catch (Exception $e) {
return response()->json($e->getMessage(), 500);
}
}
To summarise, your problem came from route definition. Your route from Axios did not match the route definition from Laravel, hence the 405.
I was having issue to send data as model while making delete request. I found a fix as follows:
deleteCall (itemId, jsonModel) {
return api.delete(`/users/${itemId}/accounts/`, {data: jsonModel})
},
Deleting users in array
Other good option, is to convert javascript array to string, and pass it has the required parameter, instead of passing object. Here the example:
In Vue.js 2.5.17+
//Use the javascript method JSON.stringify to convert the array into string:
axios.delete('api/users/' + JSON.stringify(this.checkedNames))
In Laravel 5.3+
//Resource default route (you don't need to create, it already exists)
Route::delete('api/users/{id}', 'UserController#destroy');
//In laravel delete method, convert the parameter to original array format
public function destroy($id)
{
User::destroy(json_decode($id); //converting and deleting users in array 'id'
}
Deleting single user by id
Just pass the id. You don't need to convert it.
In Vue.js 2.5.17+
axios.delete('api/users/' + id)
In Laravel 5.3+
You can name the parameter as you wish: user, id, item ,...
In Laravel 5.6+ < is named as $id //this can be the id or the user object
In Laravel 5.7+ > is named as $user //this can be the id or the user object
public function destroy($id)
{
User::destroy($id);
}
axios.post('/myentity/839', {
_method: 'DELETE'
})
.then( response => {
//handle success
})
.catch( error => {
//handle failure
})
https://www.mikehealy.com.au/deleting-with-axios-and-laravel/
i want to insert data to db using POST request
table food_directory
id (auto incremenat)
name
fructose
polylos
fructan
public function postDirec()
{
if (\Request::ajax()) {
$FodMaps = \Request::get('name');
\DB::table('food_directory')->insert([
'food_directory' => $FodMaps,
]);
}
}
Route
Route::post('postDirec', 'FodMapController#postDirec');
this will return Tokenmismatch issue.. please advice
You need to add the CSRF-token in your form, by adding this line somewhere between your form's opening and closing tag:
{!! csrf_field() !!}
Goto App\Http\Kernel.php
And comment out this line
\App\Http\Middleware\VerifyCsrfToken::class,
It should be Line 20 in that file if you haven't made any other changes.
if you want to disable csrf protection on certain routes you can to this approach.
in the app/Http/Middlewares/VerifyCsrfToken.php modify handle method to
//disable CSRF check on following routes
$skip = [
'/your-uri/you-want-to-disable-protection-for',
route('or_some_route')
];
foreach ($skip as $route) {
if ($request->is($route)) {
return $this->addCookieToResponse($request, $next($request));
}
}
return parent::handle($request, $next);
Put uri you want to disable into the skip array. It will then call the parent's class addCookieToResponse method that will set CSRF token to the cookie and request would be treated as protected.