0

0

授权:了解 Laravel 中的策略

聖光之護

聖光之護

发布时间:2024-10-18 22:21:37

|

849人浏览过

|

来源于dev.to

转载

控制用户在应用程序中可以执行或不能执行的操作是构建实际应用程序时需要做的最重要的事情之一。

例如,在待办事项应用程序中,您不希望用户能够编辑或删除其他用户的待办事项。

在本文中,您将学习在 laravel 中实现此目的的无缝方法之一,即使用策略来控制用户可以通过构建简单的待办事项应用程序执行哪些操作。

要学习本教程,您需要对 laravel 及其应用程序结构有基本的了解。

创建基础应用程序

运行以下命令在所需文件夹中创建一个新的 laravel 应用程序并移入其中:

composer create-project laravel/laravel todo-app && cd todo-app

接下来,运行以下命令来安装 laravel breeze:

php artisan breeze:install

breeze 将通过身份验证构建您的新应用程序,以便您的用户可以注册、登录、注销和查看他们的个性化仪表板。

之后,通过运行以下命令编译您的应用程序资产:

npm install && npm run dev

laravel 默认情况下附带基于文件的 sqlite 数据库,因此您需要做的下一件事是将应用程序数据库文件连接到数据库查看器,例如 tableplus 或任何其他您喜欢的数据库查看器。

将数据库连接到查看器后,运行以下命令将可用表迁移到数据库中:

php artisan migrate

完成后,运行以下命令在浏览器中查看您的应用程序:

php artisan serve

您现在应该在 localhost:8000 上看到新的 laravel 应用程序,如下所示:

授权:了解 Laravel 中的策略

您现在可以转到注册页面创建用户并访问仪表板,这是此时的整个应用程序。

模型设置

laravel 中的模型用于控制数据库表。使用以下命令在 app/models 文件夹中创建 todo 模型:

php artisan make:model todo

接下来,在新创建的文件中,用以下代码替换 todo 类:

class todo extends model
{
    use hasfactory;

    protected $fillable = [
        'title',
        'description',
        'completed',
        'user_id'
    ];

    public function user()
    {
        return $this->belongsto(user::class);
    }
}

上面的代码将使用户能够提交具有 $fillable 属性的表单;它还定义了用户和待办事项之间的关系;在这种情况下,待办事项属于用户。让我们通过将以下代码添加到 app/models/user.php 文件来完成关系设置:

    public function todos()
    {
        return $this->hasmany(todo::class);
    }

上面的代码将 user 模型连接到 todo 模型,以便它可以有很多待办事项。

迁移设置

laravel 中的迁移用于指定数据库表中应包含的内容。运行以下命令在 database/migrations 文件夹中创建迁移:

php artisan make:migration create_todos_table

接下来,将新文件中的 up 函数替换为以下内容,该函数会将 todo 表添加到数据库中,其中包含 id、user_id、title、description、completed 和 timestamp 列:

   public function up(): void
    {
        schema::create('todos', function (blueprint $table) {
            $table->id();
            $table->foreignid('user_id')->constrained()->ondelete('cascade');
            $table->string('title');
            $table->text('description')->nullable();
            $table->boolean('completed')->default(false);
            $table->timestamps();
        });
    }

接下来,运行以下命令将 todos 表添加到数据库中:

php artisan migrate

策略设置

laravel 中的策略允许您定义谁可以使用特定资源(在本例中为待办事项)执行哪些操作。

让我们通过使用以下命令在 app/policies 文件夹中生成 todopolicy 来看看它是如何工作的:

Dora
Dora

创建令人惊叹的3D动画网站,无需编写一行代码。

下载
php artisan make:policy todopolicy --model=todo

接下来,在新创建的 todopolicy 文件中,将 todopolicy 类替换为以下代码:

class todopolicy
{
    /**
     * determine if the user can view any todos.
     */
    public function viewany(user $user): bool
    {
        return true;
    }

    /**
     * determine if the user can view the todo.
     */
    public function view(user $user, todo $todo): bool
    {
        return $user->id === $todo->user_id;
    }

    /**
     * determine if the user can create todos.
     */
    public function create(user $user): bool
    {
        return true;
    }

    /**
     * determine if the user can update the todo.
     */
    public function update(user $user, todo $todo): bool
    {
        return $user->id === $todo->user_id;
    }

    /**
     * determine if the user can delete the todo.
     */
    public function delete(user $user, todo $todo): bool
    {
        return $user->id === $todo->user_id;
    }
}

上面的代码指定用户可以创建待办事项,但只能查看、更新或删除属于自己的待办事项。

接下来,让我们在下一节中设置控制器。

控制器设置

laravel 中的控制器控制应用程序针对特定资源的功能。运行以下命令在 app/http/controllers 中生成 todocontroller:

php artisan make:controller todocontroller

在新建的todocontroller文件顶部添加以下代码,导入用于数据库操作的todo模型和用于授权的gate类:

use app\models\todo;
use illuminate\support\facades\gate;

指数法

将索引方法替换为以下代码,以获取并返回所有登录用户的待办事项:

    public function index()
    {
        gate::authorize('viewany', todo::class);
        $todos = auth()->user()->todos;
        return view('todos.index', compact('todos'));
    }

gate::authorize 方法验证用户是否使用您在上一节中定义的 viewany 策略方法登录。

创建方法

将 create 方法替换为以下代码,以验证用户是否已登录,然后再将创建待办事项表单返回给用户,以便他们可以创建待办事项:

    public function create()
    {
        gate::authorize('create', todo::class);
        return view('todos.create');
    }

储存方式

用以下代码替换 store 方法,检查用户是否可以创建待办事项、验证请求、创建待办事项并将用户重定向到待办事项列表页面:

public function store(request $request)
    {
        gate::authorize('create', todo::class);

        $validated = $request->validate([
            'title' => 'required|max:255',
            'description' => 'nullable'
        ]);

        $todo = auth()->user()->todos()->create($validated);

        return redirect()->route('todos.index')
            ->with('success', 'todo created successfully');
    }

编辑方法

将编辑方法替换为以下代码,以验证用户是否可以编辑该待办事项,然后将填充了所选待办事项的编辑待办事项表单返回给用户,以便他们可以对其进行编辑:

    public function edit(todo $todo)
    {
        gate::authorize('update', $todo);
        return view('todos.edit', compact('todo'));
    }

更新方法

用以下代码替换 update 方法,检查用户是否可以更新待办事项、验证请求、更新选定的待办事项并将用户重定向到待办事项列表页面:

    public function update(request $request, todo $todo)
    {
        gate::authorize('update', $todo);

        $validated = $request->validate([
            'title' => 'required|max:255',
            'description' => 'nullable'
        ]);

        $todo->update($validated);

        return redirect()->route('todos.index')
            ->with('success', 'todo updated successfully');
    }

销毁方法

用以下代码替换 destroy 方法,检查用户是否可以删除该待办事项,删除它,并将用户重定向到待办事项列表页面:

    public function destroy(todo $todo)
    {
        gate::authorize('delete', $todo);

        $todo->delete();

        return redirect()->route('todos.index')
            ->with('success', 'todo deleted successfully');
    }

您的 todocontroller 文件现在应该如下所示:

<?php

namespace app\http\controllers;

use app\models\todo;
use illuminate\support\facades\gate;
use illuminate\http\request;

class todocontroller extends controller
{
    public function __construct()
    {
        //
    }

    public function index()
    {
        gate::authorize('viewany', todo::class);
        $todos = auth()->user()->todos;
        return view('todos.index', compact('todos'));
    }

    public function create()
    {
        gate::authorize('create', todo::class);
        return view('todos.create');
    }

    public function store(request $request)
    {
        gate::authorize('create', todo::class);

        $validated = $request->validate([
            'title' => 'required|max:255',
            'description' => 'nullable'
        ]);

        $todo = auth()->user()->todos()->create($validated);

        return redirect()->route('todos.index')
            ->with('success', 'todo created successfully');
    }

    public function edit(todo $todo)
    {
        gate::authorize('update', $todo);
        return view('todos.edit', compact('todo'));
    }

    public function update(request $request, todo $todo)
    {
        gate::authorize('update', $todo);

        $validated = $request->validate([
            'title' => 'required|max:255',
            'description' => 'nullable'
        ]);

        $todo->update($validated);

        return redirect()->route('todos.index')
            ->with('success', 'todo updated successfully');
    }

    public function destroy(todo $todo)
    {
        gate::authorize('delete', $todo);

        $todo->delete();

        return redirect()->route('todos.index')
            ->with('success', 'todo deleted successfully');
    }
}

视图设置

现在您的 todocontroller 方法已全部设置完毕,您现在可以通过在 resources/views 文件夹中创建一个新的 todos 文件夹来为您的应用程序创建视图。之后,在新的todos文件夹中创建create.blade.php、edit.blade.php、index.blade.php文件。

索引视图

将以下代码粘贴到index.blade.php中:

<x-app-layout>
    <x-slot name="header">
        <h2 class="text-xl font-semibold leading-tight text-gray-800">
            {{ __('todos') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
            <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    {{-- <div class="mb-4">
                        <a href="{{ route('todos.create') }}" 
                           class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
                            create new todo
                        </a>
                    </div> --}}

                    <div class="mt-6">
                        @foreach($todos as $todo)
                            <div class="mb-4 p-4 border rounded">
                                <h3 class="text-lg font-semibold">{{ $todo->title }}</h3>
                                <p class="text-gray-600">{{ $todo->description }}</p>
                                <div class="mt-2">
                                    <a href="{{ route('todos.edit', $todo) }}" 
                                       class="text-blue-500 hover:underline">edit</a>

                                    <form action="{{ route('todos.destroy', $todo) }}" 
                                          method="post" 
                                          class="inline">
                                        @csrf
                                        @method('delete')
                                        <button type="submit" 
                                                class="ml-2 text-red-500 hover:underline"
                                                onclick="return confirm('are you sure?')">
                                            delete
                                        </button>
                                    </form>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

创建视图

将以下代码粘贴到 create.blade.php 中:

<x-app-layout>
    <x-slot name="header">
        <h2 class="text-xl font-semibold leading-tight text-gray-800">
            {{ __('create todo') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
            <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form action="{{ route('todos.store') }}" method="post">
                        @csrf

                        <div class="mb-4">
                            <label for="title" class="block text-gray-700">title</label>
                            <input type="text" 
                                   name="title" 
                                   id="title" 
                                   class="w-full px-3 py-2 border rounded"
                                   required>
                        </div>

                        <div class="mb-4">
                            <label for="description" class="block text-gray-700">description</label>
                            <textarea name="description" 
                                      id="description" 
                                      class="w-full px-3 py-2 border rounded"></textarea>
                        </div>

                        <div class="flex items-center">
                            <button type="submit" 
                                    class="px-4 py-2 text-white bg-green-500 rounded hover:bg-green-600">
                                create todo
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

编辑视图

将以下代码粘贴到 edit.blade.php 中:

<x-app-layout>
    <x-slot name="header">
        <h2 class="text-xl font-semibold leading-tight text-gray-800">
            {{ __('edit todo') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
            <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    <form action="{{ route('todos.update', $todo) }}" method="post">
                        @csrf
                        @method('put')

                        <div class="mb-4">
                            <label for="title" class="block text-gray-700">title</label>
                            <input type="text" 
                                   name="title" 
                                   id="title" 
                                   value="{{ $todo->title }}"
                                   class="w-full px-3 py-2 border rounded"
                                   required>
                        </div>

                        <div class="mb-4">
                            <label for="description" class="block text-gray-700">description</label>
                            <textarea name="description" 
                                      id="description" 
                                      class="w-full px-3 py-2 border rounded">{{ $todo->description }}</textarea>
                        </div>

                        <div class="flex items-center">
                            <button type="submit" 
                                    class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
                                update todo
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

路线设置

使用 laravel 中的资源方法处理 todocontroller 的路由相对简单。通过将以下代码添加到 paths/web.php 文件夹的末尾来实现此目的,如下所示:

// rest of the file
Route::middleware(['auth'])->group(function () {
    Route::resource('todos', TodoController::class);
});

上面的代码使用了 auth 中间件来保护 todos 资源。登录后,您现在应该能够在应用程序中访问以下路线:

  • /todos: 列出所有用户的待办事项
  • /todos/create: 显示创建待办事项的表单
  • /todos/edit/1:显示用于编辑给定 id 的待办事项的表单;在本例中为 1。

您现在可以创建、编辑和删除待办事项,但在编辑和删除时只能以登录用户和所选待办事项的所有者身份进行。

结论

就是这样!您刚刚创建了一个真实的待办事项应用程序,该应用程序允许用户仅创建、查看、编辑和删除自己的待办事项。如果您有任何更正、建议或问题,请在评论中告诉我!

最后,记得在 dev、linkedin 和 twitter 上关注我。非常感谢您的阅读,我们下一篇再见!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
laravel组件介绍
laravel组件介绍

laravel 提供了丰富的组件,包括身份验证、模板引擎、缓存、命令行工具、数据库交互、对象关系映射器、事件处理、文件操作、电子邮件发送、队列管理和数据验证。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

339

2024.04.09

laravel中间件介绍
laravel中间件介绍

laravel 中间件分为五种类型:全局、路由、组、终止和自定。想了解更多laravel中间件的相关内容,可以阅读本专题下面的文章。

293

2024.04.09

laravel使用的设计模式有哪些
laravel使用的设计模式有哪些

laravel使用的设计模式有:1、单例模式;2、工厂方法模式;3、建造者模式;4、适配器模式;5、装饰器模式;6、策略模式;7、观察者模式。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

772

2024.04.09

thinkphp和laravel哪个简单
thinkphp和laravel哪个简单

对于初学者来说,laravel 的入门门槛较低,更易上手,原因包括:1. 更简单的安装和配置;2. 丰富的文档和社区支持;3. 简洁易懂的语法和 api;4. 平缓的学习曲线。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

385

2024.04.10

laravel入门教程
laravel入门教程

本专题整合了laravel入门教程,想了解更多详细内容,请阅读专题下面的文章。

140

2025.08.05

laravel实战教程
laravel实战教程

本专题整合了laravel实战教程,阅读专题下面的文章了解更多详细内容。

85

2025.08.05

laravel面试题
laravel面试题

本专题整合了laravel面试题相关内容,阅读专题下面的文章了解更多详细内容。

80

2025.08.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

428

2026.03.04

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

3

2026.03.11

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Laravel---API接口
Laravel---API接口

共7课时 | 0.6万人学习

PHP自制框架
PHP自制框架

共8课时 | 0.6万人学习

PHP面向对象基础课程(更新中)
PHP面向对象基础课程(更新中)

共12课时 | 0.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号