Laravel Eloquent delete by id - php

I'm trying to delete a single record by id. Instead, it deletes all records in that table.
Here's my code:
View
<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
<button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Routes
Route::post('/status/{statusId}/delete', [
'uses' => '\Dashboard\Http\Controllers\StatusController#deleteStatus',
'as' => 'status.delete',
'middleware' => ['auth'],
]);
Controller
public function deleteStatus(Request $request, $statusId)
{
Auth::user()->statuses()->delete($statusId);
return redirect()->route('home')->with('success', 'Post deleted.');
}
Note: When I dd($statusId) it does provide the right ID for the status I'm deleting. So that part does work.

This is possible in Laravel 5.6 using the destroy method:
From the docs:
However, if you know the primary key of the model, you may delete the
model without retrieving it. To do so, call the destroy method
App\Model::destroy(1);
or to delete an array of ids:
App\Model::destroy([1, 2, 3]);
or by query:
App\Model::where('active', 0)->delete();

Unfortunately, the Eloquent builder does not support passing the id to delete.
Instead, you have to first find to model, then call delete on it:
$request->user()->statuses()->findOrFail($statusId)->delete();

you can delete the model by using another approach like
App\Models\ModelName::find(id)->delete()
but it throws nullPointerException that you have to handle

**Step 1 create route inside web.php**
Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');
**Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
{
$ans = Answer::find($id);
$ans->delete();
session()->flash('success', 'Answer Deleted Successfully!!!');
return view('admin.anser.index');
}
**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*
<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>

Related

The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST. in laravel

i want to do seller can delete the product
<form action="{{ route('product.destroy'}}" method="post">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit" class="btn btn-sm btn-danger">Delete</button>
</form>
this is in web.php
Route::get('/index', 'ProductController#index');//seller view all product
Route::get('/create', 'ProductController#create'); //seller create new product
Route::post('','ProductController#store')->name('product.store'); //store in database
Route::get('/edit/{id}','ProductController#edit'); // seller edit post
Route::put('edit/{id}','ProductController#update')->name('product.update'); //seller update
Route::delete('/{id}','ProductController#destroy')->name('product.destroy');//seller delete product
this is in ProductController
public function destroy($id)
{
$product= Product::find($id);
Storage::delete($product->image);
$product->delete();
return back()->withInfo('Product has been deleted');
}
HELP me please
I think you are missing ID do it like
{{ route('product.destroy', $product->id)}}
you can try removing the post method of the form cause you specify another one and depend on which version you are using you can try #method('DELETE')
#method('DELETE')
it just more elegant
Pass the ID in the route in form tags,
{{ route('product.destroy', $product->id)}}
Also
$product= Product::find($id);
Storage::delete($product->image);
$product->delete();
Check if their is a $product, then delete it, otherwise you'll get an error.

Laravel Exception 405 MethodNotAllowed

I'm trying to create a new "Airborne" test in my program and getting a 405 MethodNotAllowed Exception.
Routes
Route::post('/testing/{id}/airbornes/create', [
'uses' => 'AirborneController#create'
]);
Controller
public function create(Request $request, $id)
{
$airborne = new Airborne;
$newairborne = $airborne->newAirborne($request, $id);
return redirect('/testing/' . $id . '/airbornes/' . $newairborne)->with(['id' => $id, 'airborneid' => $newairborne]);
}
View
<form class="sisform" role="form" method="POST" href="{{ URL::to('AirborneController#create', $id) }}">
{{ csrf_field() }}
{!! Form::token(); !!}
<button type="submit" name="submit" value="submit" class="btn btn-success">
<i class="fas fa-plus fa-sm"></i> Create
</button>
</form>
According to my knowledge forms don't have a href attribute. I think you suppose to write Action but wrote href.
Please specify action attribute in the form that you are trying to submit.
<form method="<POST or GET>" action="<to which URL you want to submit the form>">
in your case its
<form method="POST" ></form>
And action attribute is missing. If action attribute is missing or set to ""(Empty String), the form submits to itself (the same URL).
For example, you have defined the route to display the form as
Route::get('/airbornes/show', [
'uses' => 'AirborneController#show'
'as' => 'airborne.show'
]);
and then you submit a form without action attribute. It will submit the form to same route on which it currently is and it will look for post method with the same route but you dont have a same route with a POST method. so you are getting MethodNotAllowed Exception.
Either define the same route with post method or explicitly specify your action attribute of HTML form tag.
Let's say you have a route defined as following to submit the form to
Route::post('/airbornes/create', [
'uses' => 'AirborneController#create'
'as' => 'airborne.create'
]);
So your form tag should be like
<form method="POST" action="{{ route('airborne.create') }}">
//your HTML here
</form>
MethodNotAllowedHttpException signposts that your route isn't available for the HTTP request method specified. Perhaps either because it isn’t defined correctly, or it has a conflict with another similarly named route.
Named Routes
Consider using named routes to allow for the convenient generation of URLs or redirects. They can generally be much easier to maintain.
Route::post('/airborne/create/testing/{id}', [
'as' => 'airborne.create',
'uses' => 'AirborneController#create'
]);
Laravel Collective
Use Laravel Collective's Form:open tag and remove Form::token()
{!! Form::open(['route' => ['airborne.create', $id], 'method' =>'post']) !!}
<button type="submit" name="submit" value="submit" class="btn btn-success">
<i class="fas fa-plus fa-sm"></i> Create
</button>
{!! Form::close() !!}
dd() Helper Function
The dd function dumps the given variables and ends execution of the script. Double-check your Airborne class is returning the object or id you expect.
dd($newairborne)
List available routes
Always make sure your defined routes, views, and actions match up.
php artisan route:list --sort name
First of All
Form don't have href attribute, it has "action"
<form class="sisform" role="form" method="POST" action="{{ URL::to('AirborneController#create', $id) }}">
Secondly
If the above change doesn't work, you can make some changes like:
1. Route
Give your route a name as:
Route::post('/testing/{id}/airbornes/create', [
'uses' => 'AirborneController#create',
'as' => 'airborne.create', // <---------------
]);
2. View
Give route name with route() method in form action rather than URL::to() method:
<form class="sisform" role="form" method="POST" action="{{ route('airborne.create', $id) }}">

trouble with deleting a record with laravel delete function

I have a problem with laravel and deleting.
Basically this should delete a row from database but when i click on delete it redirects me back but it doesn't delete what it should
Here is the code im working on
<div class="list-group">
#forelse($categories as $category)
<h4>{{$category->name}}</h4>
<form action="{{route('categories.destroy', $category->id)}}" method="POST" class="inline-it">
{{csrf_field()}}
{{method_field('DELETE')}}
<input class="btn btn-xs btn-danger" type="submit" value="Delete">
</form>
<hr>
#empty
<h5> - No categories.</h5>
#endforelse
</div>
route:
Route::resource('/categories','CategoriesController');
controller:
public function destroy(Categories $categories)
{
$categories->delete();
return back();
}
edit dd https://pastebin.com/s41djcUH
edit
Just change $categories with $category
public function destroy(Categories $category)
{
$category->delete();
return back();
}
For Implicit Route Model Binding:
https://laravel.com/docs/master/routing#route-model-binding
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

how to print the database content on a desired page?

I am using laravel 5.2. I want to print the database content that is stored in my database dynamically on the desired page. I tried but an error appears everytime i.e;( undefined variable:). I just want to print whatever content I store in my database table dynamically.
My code is here:
My model name is:gallery
My routes:
Route::get('/gallery/list' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/gallery/save' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);
My controller:
public function viewgallerylist()
{
$galleries = gallery::all();
return view('gallery')->with('galleries', $galleries);
}
public function savegallery(Request $request)
{
$gallery1=$request['gallery_name'];
$gallery=new gallery();
$gallery->name=$gallery1;
$gallery->save();
return redirect()->route('viewgallery');
}
My desired page:
<form method="post" action="{{ route('savegallery') }}">
<input class="form-control" type="text" name="gallery_name">
<button type="submit" class="btn btn-primary" id="upl">Create+</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
#foreach($galleries as $gallery)
<p>{{ $gallery->name }}</p>
#endforeach
Most model Classes will have a capital letter. Are you sure your Model isn't called Gallery instead of gallery?
which means that you need to call Gallery::all() in your controller and make sure use App\Gallery; is at the top of your page.
public function viewgallerylist()
{
$galleries = Gallery::all();
return view('gallery')->with('galleries', $galleries);
}
The problem might be with your model.... please provide a larger view
Route::get('/' ,[
'uses'=>'gallerycontroller#viewgallerylist',
'as'=>'viewgallery'
]);
Route::post('/' ,[
'uses'=>'gallerycontroller#savegallery',
'as'=>'savegallery'
]);

delete data from database using model in laravel 5

I am trying to delete data from my table employes by getting the id of the data and transferring it by using get route but i get the following error
ModelNotFoundException in Builder.php line 125: No query results for
model [App\employe].
her is my route
Route::get('/delete/{employe}', 'EmployeController#delete');
Route::post('/delete', 'EmployeController#handleDelete');
and i have model called employe to access my table
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class employe extends Model {
protected $fillable = array('fname','lname','age','sex','phone','email','houseno','city','kebele','state','username','password','workposition','salary','bankaccount','bankname','contactid','employedate');
}
part of my controller for deleting
public function delete(employe $employe)
{
// Show delete confirmation page.
return View('deleteemploye', compact('employe'));
}
public function handleDelete()
{
$employe = employe::findOrFail(Input::get('employe'));
$employe->delete();
return Redirect::action('EmployeController#index');
}
her is my view for deleting file
#extends('app')
#section('content')
<div class="page-header">
<h2>Delete {{$employe->fname}} Are you sure?</h2>
</div>
<form action="{{ action('EmployeController#handleDelete') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="employe" id="employe" value="{{ $employe->id }}" />
<input type="submit" class="btn btn-default" value="Yes" />
No
</form>
#stop
Looks like laravel cant find the model with the primary key you are passing. Check the database and see if its there. If it is check the deleted_at field. If it has a date in it, it means it is already deleted. You can still find it by using withTrashed()
$employe = employe::withTrashed()->findOrFail(Input::get('employe'));
and if you have soft deleting enabled for this model, you can completely remove the given row by running
$employe = employe::withTrashed()->findOrFail(Input::get('employe'))->forceDelete();

Categories