定制 smashed-egg/laravel-auth-route-bindings 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

smashed-egg/laravel-auth-route-bindings

最新稳定版本:1.2.0

Composer 安装命令:

composer require smashed-egg/laravel-auth-route-bindings

包简介

Adds support for creating Route Model bindings to an authenticated user in Laravel

README 文档

README

Laravel Auth Route Bindings

Latest Stable Version Downloads this Month

This package allows you to create route model bindings that also use the authenticated user to retrieve the model.

For example. You might want to check that the Post model requested belongs to the User that's logged in. Previously you might have done something like the following:

Route::get('posts/{post}', function (Post $post) {
    abort_unless($post->user_id === auth()->user()->getAuthIdentifier());
    return $post;
});

or

Route::get('posts/{id}', function ($id) {
    $post = Post::where('user_id', auth()->user()->getAuthIdentifier())->findOrFail($id);
    return $post;
});

or using Policies:

<?php
 
namespace App\Policies;
 
use App\Models\Post;
use App\Models\User;
 
class PostPolicy
{
    /**
     * Determine if the given post can be updated by the user.
     */
    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }
}

Policies have the disadvantage of returning data from the database, hydrating a model, then comparing, and in the case where the user doesn't have access to it, its then thrown away.

This package has the added benefit whereby the logic is done all at the database level.

Requirements

  • PHP 8.0.2+
  • Laravel 9.0+

Installation

To install this package please run:

composer require smashed-egg/laravel-auth-route-bindings

Support Me

Do you like this package? Does it improve you're development. Consider sponsoring to help with future development.

Buy me a coffee!

Thank you!

Usage

You should define your model bindings at the beginning of the boot method of your RouteServiceProvider.

For example:

use App\Models\Post;
use Illuminate\Support\Facades\Route;
 
/**
 * Define your route model bindings, pattern filters, etc.
 */
public function boot(): void
{
    Route::modelAuth('post', Post::class);
 
    // ...
}

And then you can use in your routes declarations the same way as you use other model bindings:

Route::get('posts/{post}', function (Post $post) {
    return $post;
});

You can even use it with scoped bindings:

Route::get('posts/{post}/comments/{comment}', function (Post $post, Comment $comment) {
    //..
})->scopeBindings();

So the Post must belong to the authenticated User, and the Comment must belong to the Post.

统计信息

  • 总下载量: 2.78k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 1
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-07-06