I made a user management system with soft deletion and force deletion options. However, I'm having trouble getting the force deletion option to work.
The route:
Route::post('users/{user}/delete', 'UserController#forcedelete');
The relevant controller code:
public function forcedelete(User $user)
{
$user->forceDelete();
return redirect('users/trash');
}
The view code:
<a href="{{ url('users/'.$user->id.'/delete') }}"
onclick="event.preventDefault(); document.getElementById('delete').submit();">
<i class="fa fa-trash-o btn btn-danger btn-xs"></i>
</a>
<form id="delete" action="{{ url('users/'.$user->id.'/delete') }}"
method="POST" style="display: none;">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
The error that I'm getting is
MethodNotAllowedHttpException in RouteCollection.php line 233:
Why is it not working, and how can I fix it?
Try placing this route above your other user routes or user resource route. Also you're trying to use route model binding with a soft deleted model, which won't work. You need to use the id and delete it manually.
public function forcedelete($id)
{
User::where('id', $id)->forceDelete();
return redirect('users/trash');
}
Edit: Also delete {{ method_field('DELETE') }} from your form, since the route method defined is post.
Methods to remove/restore records from the table. Laravel 5.x, 6.x, 7.x
To enable soft deletes for a model, use the Illuminate\Database\Eloquent\SoftDeletes trait on the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
Soft delete:
This will move record to trash
$user= User::find($id);
$user->delete();
Force Delete: Permanently Deleting Models
$user= User::withTrashed()->find($id);
$user->forceDelete();
Restore: Restoring Soft Deleted Models
$user= User::withTrashed()->find($id);
$user->restore();
Related
I have many to many relationship between users and products table and I set up a view (welcome.blade.php) that when I click on the product name, which is a link, it is supposed to redirect me to page where my delete form is so I can delete that particular product, but I get 404 not found page. I suspect that error is somewhere in my routes but I can't seem to find the problem. Also when I click on some product my url says project/destroy/1 which I think is good. Here is my code:
web.php:
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/store', 'HomeController#store')->name('store');
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
destroy.blade.php:
<div class="col-md-12">
<form action="destroy/{{ $product->id }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
welcome.blade.php:
#if($products)
<table class="table">
<thead>
<th>#</th>
<th>Product Name</th>
<th>Owner Of The Product</th>
<th>Created At</th>
</thead>
<tbody>
#foreach ($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>
{{ $product->files }}
</td>
<td>
#foreach ($product->users as $user) {{ $user->name }}
#endforeach
</td>
<td>{{ date('M j, Y', strtotime($product->created_at)) }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
public function destroy(Product $product)
{
$product->users()->detach();
$product->delete();
return view('destroy');
}
}
You defined the following route in your file.
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
This creates a DELETE route. DELETE routes are meant to be accessed by APIs. Links in anchor tags use GET routes. Clicking on
{{ $product->files }}
makes the router try and match GET /destroy/{$id} which is not defined, so it throws either an exception if debug is on or a 404 if not. You can see this in action by looking at the network tab of your browser's developer console.
Unless you add another GET route, you'll keep getting 404s.
Route::get('/destroy/{$id}', 'HomeController#destroy')->name('product.destroy-form');
will make the following link work.
{{ $product->files }}
Also, in the destroy method you're returning the view without passing any variables but in destroy.blade.php you seem to be using $product. Don't forget to add it!
You are nearly there, you just have a step too many.
Good call on the form and using the delete method, this is absolutely what you are supposed to do
However where you are going wrong is in using the link to go to a separate page with the form on to delete. You are better using a little javascript so the link submits a hidden form from the link.
<a onclick="document.getElementById('delete-form-{{$product->id}}').submit();}">{{ $product->files }}</a>
<form id="delete-form-{{$product->id}}" action="{{ route('destroy', ['id' => $product->id]) }}" method="POST" style="display: none;">
#csrf
#method('delete')
</form>
You can do the method you have but you need an additional route::get request to a page that loads the form and then you can submit the form on that page to delete.
I think it is because to delete a product using a new page the first thing to do is navigate to that page which you are not doing. You are instead going directly to the delete function using this
Route::delete('/destroy/{$id}', 'HomeController#destroy')->name('destroy');
You need to define a route that lets you go to that page first which u can do by creating a route like this:
Route::get('/delete/{$id}', 'HomeController#delete')->name('delete');
You should create a new function delete in the HomeController that just returns the destroy.blade.php. Something like this.
$product= Product::find($id);
return view('destroy')->with('product', $product);
where $id is the product id and Product is the model that you are using.
I have a route which was working perfectly.
Route::get('/advertise', 'AdvertisementController#index')->middleware('auth');
When i added the middleware and tried to access the advertise page i got the following error.
Undefined variable: user (View: C:\Users\andre\Dropbox\College\Project\Rentable\resources\views\layouts\main.blade.php
This is the main layout
<header>
<div class="container"><a class="logo" href="/">Rentable</a>
<nav>
#guest
Register
Login
Advertise Your Property
#else
Advertise Your Property
{{$user->name}}
<a href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
#endguest
</nav>
</div>
</header>
This is the index of the advert controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PropertyAdvert;
use DB;
use Auth;
class AdvertisementController extends Controller
{
public function index(){
return view('pages/Advert/create');
}
}
Change your controller code to match the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\PropertyAdvert;
use DB;
use Auth;
class AdvertisementController extends Controller
{
public function index(){
return view('pages/Advert/create', [
'user' => Auth::user(),
]);
}
}
You have to pass the user to the view in order to use it then in {{ $user->name}}
Alternatively if your $user is being passed to numerous pages take a look at composer service providers here: https://laravel.com/docs/5.6/providers
I am trying to update my data, but i keep getting this error message:
"Trying to get property of non-object (View: C:\xampp\htdocs\blog\resources\views\update.blade.php)".
This is my update.blade.php file
#extends ('layout')
#section ('title')
Update page
#stop
#section ('content')
<div class="row">
<div class="col-lg-12">
<form action="/todo/save" method="post">
{{ csrf_field() }}
<input type="text" class="form-control input-lg" name="todo"
value="{{ $todo->todo }}" placeholder="Type in to create a new todo">
</form>
</div>
</div>
<hr>
#foreach ($todo as $todo)
{{ $todo->todo }} <a href="{{ route('todo.update', ['id' =>$todo->id])
}}" class="btn btn-info btn-sm">Update</a> <a href="{{ route('todo.delete',
['id' =>$todo->id]) }}"class="btn btn-danger">Delete</a>
<hr>
#endforeach
#stop
my controller:
public function update($id){
//dd($id);
$todo = Todo::find($id);
return view('update')->with('todo', $todo);
}
and finally my update route:
Route::get('/todo/update/{id}', 'TodosController#update')-
>name('todo.update');
This is just some basic stuff, but im stuck in here for couple of hours now, and any help is highly appreciated!
Use findOrFail method on your controller to throw an Exception if $todo is empty
public function update($id){
$todo = Todo::findOrFail($id);
return view('update', compact('todo'));
}
The problem is also on your update.blade.php file. foreach $todo as todo, $todo has collection of eloquent model or eloquent model ? I think it's a eloquent model. So a loop doesnt have any sense.
That error would happen if todo were FALSE or some other non-object.
You can inspect it with a var_dump($todo);die(); in the controller.
find() will return either null or the model that is found. Assuming that the model is found, you're doing a for each on that model (foreach ($todo...)), which will iterate over the model's public properties. This is obviously not what you intend to do.
It looks to me like you're trying to loop over a list of your todos and print out edit/delete links. If this is the case, you need to get the list of your todos in your controller, pass it into your view, and fix your foreach statement.
Controller:
$todos = Todo::get();
// pass to view
View:
foreach ($todos as $todo)
I'm using multi auth for Laravel ...
This is my lougout function for users
LoginController
public function logout()
{
Auth::guard('web')->logout();
return redirect('/');
}
AdminloginController
public function logout()
{
Auth::guard('web')->logout();
return redirect('/');
}
This is my route
Route::get('/enseignant/logout', 'Auth\LoginController#Elogout')->name('enseignant.logout');
Route::get('/administration/logout', 'Auth\AdminloginController#logout')->name('admin.logout');
All the methods in the view
<a href="{{ route('admin.logout') }}" class="btn btn-default btn-flat"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('admin.logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
The function works fine but when I click the button I get this error :
MethodNotAllowedHttpException in RouteCollection.php line 233
Your route accepts only GET method, but in the form, you specified using POST. I think this is the source of the problem. The error message also indicates that.
It's recommended to use POST for logout, as you did. So, just by changing the route in question to...
Route::post(...);
... should fix the error.
I have a problem with Larave's framework program with deleting by CRUDS method DELETE.
My route method is:
Route::delete('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete(); return redirect('cats.index')
->withSuccess('Cat
has been deleted.'); });
My view with delete url:
#extends('layouts.master')
#section('header')
Back to the overview
<h2>
{{ $cat->name }}
</h2>
<a href="{{ url('cats/'.$cat->id.'/edit') }}">
<span class = "glyphicon glyphicon-edit"></span>
Edit
</a>
<a href ="{{ url('cats/'.$cat->id.'/delete') }}">
<span class ="glyphicon glyphicon-trash"></span>
Delete
</a>
<p>Last edited: {{ $cat->updated_at }}</p>
#endsection
#section('content')
<p>Date of Birth: {{ $cat->date_of_birth }} </p>
<p>
#if ($cat->breed)
Breed:
{{ url('cats/breeds/'.$cat->breed->name) }}
#endif
</p>
#endsection
My Cat model:
<?php
namespace Furbook;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model {
// We specified the fields that are fillable in the Cat model beforehand
protected $fillable = ['name','date_of_birth','breed_id'];
// informacja o tym, żeby nie uaktualniać update_at w tabeli kotów
public $timestamps = false;
public function breed(){
return $this->belongsTo('Furbook\Breed');
}
}
?>
When I'm clicking on delete link, there is an error like this:
MethodNotAllowedHttpException in RouteCollection.php line 233:
I don't know what's wrong. Could you somoene help me with solving problem?
Could someone help me with this problem?
I would be very grateful, greetings.
This is to do with the Request you are making. You must either create form with the delete method like so
<form action="{{ url('cats/'.$cat->id.'/delete') }}" method="DELETE">
<button class ="glyphicon glyphicon-trash">Delete</button>
</form>
OR change your route to a get
Route::get('cats/{cat}/delete', function(Furbook\Cat $cat){
$cat->delete();
return redirect('cats.index')->withSuccess('Cat has been deleted.');
});
If you go the form route don't for get to add the {{ csrf_field() }}
https://laravel.com/docs/5.4/csrf
Using Route::delete(), you cannot place it in an anchor. Make a form with DELETE method.
{!! Form::model($cat, ['method' => 'DELETE', 'url' => 'cats/'.$cat->id.'/delete']) !!}
<button type="submit">Delete</a>
{!! Form::close() !!}