Having bug with destroy and update method in Laravel - php

I'm trying to create simple Laravel application to use resource controller, but i'm having some kind of bug in update and destroy method when I pass the object itself to method.
My update and destroy functions are simple, they just take $todoList and either updates or deletes that object. However, they seem not working as expected. I try to dd($todoList) and it returns correct value, but does not update the database.
public function update(TodoList $todoList)
{
$todoList->update(['completed' => 1]);
return redirect()->route('todos.index');
}
public function destroy(TodoList $todoList)
{
$todoList->delete();
return redirect()->route('todos.index');
}
My blade template looks like this:
<form action="{{route('todos.destroy', $todo)}}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-link btn-sm float-end"><i class="fas fa-trash"></i></button>
</form>
<form action="{{route('todos.update', $todo)}}" method="POST">
<span #class([$todo->completed ? 'bg-success':''])>{{$todo->content}}</span>
#csrf
#method('PATCH')
<button type="submit" class="btn btn-link btn-sm float-end"><i class="fas fa-edit"></i></button>
</form>
I have also tried to pass $todo-id to route, but none seem to be working. I have checked documentation and I'm usually working with documentations, but this seems to be interesting bug to me.
My route is
Route::resource('/todos', TodoListController::class);
and finally my Model is like following
class TodoList extends Model
{
use HasFactory;
protected $fillable = ['content'];
protected $guarded = [];
}

Related

Route [crops.restore] not defined

I created a resource controller. The problem is when I code a route in my view, the browser displays Route [crops.restore] not defined. I run the php artisan route:list command and I realize that the route does not exist in the route list.
My controller is this
// Display all crops
public function index(Request $request)
{
if ($request->has('trashed')) {
$records = Crop::onlyTrashed()
->get();
} else {
$records = Crop::get();
}
return view('crops.index', compact('records'));
}
//restore a file
public function restore(Request $request, $id)
{
Crop::withTrashed()->find($id)->restore();
return redirect()->back();
}
My route
// Crop controllers
Route::resource('crops', 'CropsController');
My View
#foreach ($records as $crops)
//code ...
#if(request()->has('trashed'))
<a class="btn btn-success btn-sm float-left mr-1" href="/crops/{{ $crops['id'] }}/edit">Edit</a>
Restore
#else
<form method="POST" class="float-left" action="{{ route('crops.destroy', $crops->id) }}">
#csrf
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger delete btn-sm " title='Delete'>Delete</button>
</form>
#endif
#endforeach
What's wrong with my code?
Restore provide this methods in your controller: index, store, edit, update, show, destroy. If you want redirect to your custom method like restore your have to rewrite your route in this matter:
Route::get('/restore', [App\Http\Controllers\CropsController::class, 'restore']);
Just add the route in the web.php file. For example:
Route::get('/restore', '\App\Http\Controllers\HomeController#restore');

Why Is Method Spoofing not Working Laravel?

I have a form associated with the destroy method to delete a item/record.
<form action="{{ route('climb-excluded.destroy',$exclude->id) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-danger btn-sm">
<i class="fa fa-trash-o" aria-hidden="true"></i> Delete
</button>
</form>
destroy() method
<?php
public function destroy(Cexcluded $cexcluded)
{
$cexcluded->tours()->detach();
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
Routes
Route::resource('climb-excluded','CexcludedsController', ['only'=>['store','destroy']]);
Route::get('climbing/included-excluded','HomeController#getclimbIE')->name('climb.ie');
The trouble I'm having is the destroy method is not deleting the record from the DB and doesn't give any error. It is giving a session message without deleting the record.
I saw your other thread with the same issue regarding the detach causing problems.
Add this to your Cexcluded model
public static function boot()
{
parent::boot();
static::deleting(function($model) {
$model->tours()->detach();
});
}
Remove the following line from your controller method
$cexcluded->tours()->detach();
So try this
public function destroy(Cexcluded $cexcluded)
{
$cexcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
You must use "->destroy()" in the controller.
Check this question for clarification between destroy() and delete()

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.

Passing variable from button to controller Laravel

I am having a little routing problem in Laravel 5.2. I have a result page which shows detailed information about personnel. I would like a button, which when enabled, generates a PDF page. Passing the variables has been a problem but I am very close now! I will public my code to elaborate.
result page
<form action="generatePDFpage" method="get">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</form>
routes.php
Route::get('/dashboard/result/generatePDFpage', 'resultController#GeneratePDFc');
GeneratePDFc controller
public function GeneratePDFc(){
$id_array_implode = "HALLO";
$pdf= PDF::loadView('GeneratePDF', ["test"=>$id_array_implode])->setPaper('a4', 'landscape');
return $pdf->stream('invoice.pdf');
}
So, on the result page I am using a array ($id_array) to search the database for the matching records. I need to pass this variable onto the GeneratePDFc controller, so that I can pass that again to the loadView function!
Could someone please help me out? :-)
When you're using get method, you can do just this:
<a href="{{ route('route.name', $parameter) }}">
<button type="submit" class="btn btn-default">Generate PDF!</button>
</a>
For other methods you can use something like this (this one is for DELETE method):
<form method="POST" action="{{ route('route.name', $parameter) }}" accept-charset="UTF-8">
<input name="_method" type="hidden" value="DELETE">
{{ csrf_field() }}
<button type="submit" class="btn btn-sm btn-default">Generate PDF!</button>
<input type="hidden" value="someVariable" />
</form>
To get variable, use something like this:
public function generatePDF(Request $request)
{
$someVariable = $request->someVariable;
I don't know Laravel but I think when in your action="" of the form you can put your route with its parameters no ?
I've found it here : https://laravel.com/docs/4.2/html#opening-a-form
And access the variable in your controller using the $request var

Laravel Eloquent delete by id

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>

Categories