Laravel删除不起作用

Posted

技术标签:

【中文标题】Laravel删除不起作用【英文标题】:Laravel Delete not working 【发布时间】:2018-10-18 21:51:05 【问题描述】:

正如标题所示,我无法使 delete() 选项起作用。我在网上查了很多帖子,但没有正确的答案。 我正在使用带有 Homestead 的 Laravel 5.5(一周前安装,最新版本左右)。

让我给你一些代码,我真的希望有人能够帮助我。

这让我头疼,奥氮平快用完了。请告诉我我做错了什么,如果有什么遗漏,请告诉我!

我想以管理员身份删除一个页面,但我 Laravel 似乎没有授权我并给我这个错误:

    protected function methodNotAllowed(array $others)

    throw new MethodNotAllowedHttpException($others);

这是我的控制器:

    <?php

namespace App\Http\Controllers\Admin;

use Auth;
use App\Page;
use App\Http\Requests\WorkWithPage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PagesController extends Controller

    public function __construct() 
        $this->middleware('admin');
        $this->middleware('can:manageUsers,App\User');
    
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    
        if (Auth::user()->isAdmin()) 
            $pages = Page::paginate(20);
         else 
            $page = Auth::user()->pages()->paginate(5);
        
        return view('admin.pages.index', ['pages' => $pages]);
    

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    
        return view('admin.pages.create')->with(['model' => new Page()]);
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(WorkWithPage $request)
    
        Auth::user()->pages()->save(new Page($request->only([
            'title','url','content'])));

            return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangemaakt');
    

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function edit(Page $page)
    
        if(Auth::user()->cant('update', $page))
            return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
         

        return view('admin.pages.edit', ['model' => $page]);
    

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function update(WorkWithPage $request, Page $page)
    
        if(Auth::user()->cant('update', $page))
            return redirect()->route('pages.index')->with('status', 'Dat mag jij niet');
         

        $page->fill($request->only([
            'title','url','content'
        ]));

        $page->save();

        return redirect()->route('pages.index')->with('status', 'Pagina succesvol aangepast');
    

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Page  $page
     * @return \Illuminate\Http\Response
     */
    public function destroy(Page $page)
    
        if(Auth::user()->cant('delete', $page))
            return redirect()->route('pages.index')->with('status', 'Hey knul! Pssst! Wegwezen!');
        

        $page->id->delete();

        return redirect()->route('pages.index')->with('status', 'Page has been deleted.');
    

这是我的索引页面(后端的管理索引中的索引:

 @extends('layouts.app') @section('content')
<div class="container">
    @if (session('status'))
    <div class="alert alert-info">
         session('status') 
    </div>
    @endif
    <a href=" route('pages.create')" class="btn btn-primary">Nieuwe pagina</a>
    <br>
    <br>
    <table class="table">
        <thead>
            <tr>
                <th>Naam</th>
                <th>URL</th>
                <th>Opties</th>
            </tr>
        </thead>

        @foreach($pages as $page)
        <tr>
            <td>
                <a href=" route('pages.edit', ['page' => $page->id]) "> $page->title </a>
            </td>
            <td> $page->url </td>
            <td class="text-right">
                <a href=" route('pages.destroy', ['page' => $page->id])" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
                    data-form="delete-form">
                    Delete
                </a>
            </td>
        </tr>
        @endforeach
    </table>
    $pages->links()
</div>
<form id="delete-form" action="" methode="POST">
        method_field('DELETE') 
        !! csrf_field() !!
    </form>
@endsection

然后是路线:

   <?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () 
    return view('welcome');
);

Auth::routes();

Route::get('/admin', function() 
    return view('admin.index');
)->middleware('admin');

Route::resource('/admin/pages', 'Admin\PagesController', ['except' => ['show']]);

Route::resource('/admin/blog', 'Admin\BlogController', ['except' => ['show']]);

Route::resource('/admin/users', 'Admin\UsersController', ['except' => ['create', 'store', '']]);

Route::get('/home', 'HomeController@index')->name('home');

然后是政策:

    <?php

namespace App\Policies;

use App\User;
use App\Page;
use Illuminate\Auth\Access\HandlesAuthorization;

class PagePolicy

    use HandlesAuthorization;

    public function before($user, $ability) 
        if ($user->isAdmin()) 
            return true;
        
    
    /**
     * Determine whether the user can update the page.
     *
     * @param  \App\User  $user
     * @param  \App\Page  $page
     * @return mixed
     */
    public function update(User $user, Page $page)
    
        return $user->id = $page->user_id;
    

     /**
     * Determine whether the user can delete the page.
     *
     * @param  \App\User  $user
     * @param  \App\Page  $page
     * @return mixed
     */
    public function delete(User $user, Page $page)
    
        return $user->id = $page->user_id;
    

最后是中间件:

    <?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AccessAdmin

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    
        if(Auth::check() && Auth::user()->hasAnyRole(['Super Admin','Admin'])) 
            return $next($request);
        

        return redirect('login');
    

更新:已修复!

在我改变的视图中:

            @foreach($model as $post)
        <tr>
            <td>
                <a href=" route('blog.edit', ['post' => $post->id]) "> $post->title </a>
            </td>
            <td> $post->user()->first()->name </td>
            <td> $post->slug </td>
            <td class="text-right">
                <a href=" route('blog.destroy', ['blog' => $post->id])" class="btn btn-danger delete-link" data-message="Are you sure you want to delete this page?"
                    data-form="delete-form">
                    Delete
                </a>
            </td>
        </tr>
        @endforeach
    </table>
    $model->links()
</div>
<form id="delete-form" action="#" methode="POST">
         method_field('DELETE') 
        !! csrf_field() !!
</form>

收件人:

        @foreach($pages as $page)
    <tr>
        <td>
            <a href=" route('pages.edit', ['page' => $page->id]) "> $page->title </a>
        </td>
        <td> $page->url </td>
        <td class="text-right">
            <form action=" route('pages.destroy', ['page' => $page->id]) " method="POST" class="btn btn-danger delete-link" >
                <input type="submit" value="delete"/>
                method_field('DELETE') 
                !! csrf_field() !!
            </form>
        </td>
    </tr>
    @endforeach
</table>
$pages->links()

【问题讨论】:

删除路由在哪里?欺骗? ***.com/questions/31622818/… 这很有趣;我在网上看了一些教程,他们知道如何在没有的情况下做到这一点。我一直在搞乱路线,但没有结果。我都试图同时学习 PHP 作为 Laravel,所以无法真正理解这里的问题(在我解决这个问题后,我会更多地使用 PHP,然后是 Laravel) 想到的其他事情...发布到 GET 路线。相信日志,它会告诉你错误。 缺少路由似乎适用于编辑(和更新)。关于 POST for GET 部分:这在 tut 中有明确说明。所以我就这么做了 您已从 achor 调用删除。那会做GET 不是吗?您应该考虑使用表单和类似链接的提交按钮来达到预期的效果 【参考方案1】:

不知道从哪里开始... 首先,您收到的异常是因为您向 url 发送了错误的方法。 (我从来没有那样做)但可能你在期待 POST 时发送 GET(使用 DELETE 覆盖)。你有错误的命名“方法”,它应该是“方法”。 接下来...不确定这是否已经完成$page-&gt;id-&gt;delete();...也许$page-&gt;delete()。 作为建议-也许使用!can()而不是cant()会更好。没有区别,但cant() 在某些时候可能会让您感到困惑。 我很高兴看到有人使用-&gt;fill() 方法,但是在处理复选框时您可能会遇到一个小问题。检查这个:https://github.com/LaraModulus/admin-core/blob/master/src/traits/HelpersTrait.php

【讨论】:

感谢您的评论。我修复了“方法”类型(一半荷兰人,我觉得自己像个白痴)。我也把它当作 $page->delete();在我开始搞砸之前。还原后,实际上没有任何变化(仍在尝试用 noob 语言翻译您评论的第一部分)。

以上是关于Laravel删除不起作用的主要内容,如果未能解决你的问题,请参考以下文章

从 laravel 控制器中删除 public 后不起作用?

路线存在但不起作用,删除的路线仍然有效 Laravel

Laravel Migrations onDelete Restrict 不起作用

Laravel 迁移不起作用

Laravel 中的注册和登录表单不起作用

Axios删除不起作用