tomschlick / laravel-linkable
Laravel模型的URL绑定
v4.0
2021-07-15 18:07 UTC
Requires
- php: >=7.3
- laravel/framework: >=6.0
Requires (Dev)
- doctrine/dbal: ^2.9
- larapack/dd: ^1.0
- mockery/mockery: ~1.0
- orchestra/testbench: ^5.0
- phpunit/phpunit: ^7.0 || ^8.0 || ^9.0
This package is auto-updated.
Last update: 2024-09-18 08:01:22 UTC
README
Linkable 允许您将命名路由直接绑定到您的 Eloquent 模型。它已在 Laravel 5.0 及以上版本中进行了测试(尽管它也可能在旧版本上工作)。
每次需要生成 URL 时都调用 route()
可能很麻烦,并且会使您的 Blade 文件难以阅读。相反,使用 Linkable,您可以使用以下语法生成 URL
$model->link()
这就完成了!下面是完整的用法。
通过 Composer 安装
composer require tomschlick/laravel-linkable
添加到您的模型并实现接口
class User extends Model { use TomSchlick\Linkable\Linkable; public function sublink(string $key, array $attr = []) : string { return route("users.$key", [ 'user_id' => $this->id, // 'user_id' is the name of the parameter in the users.* route group ] + $attr); } }
用法
$model->link(); // Link for the resource (example: https://your-site.com/user/7) $model->sublink('edit'); // SubLink for the resource (example: https://your-site.com/user/7/edit) $model->sublink('photos.show', ['photo_id' => 1234]); // SubLink for the resource (example: https://your-site.com/user/7/photos/1234) $model->redirect(); // Generates a redirect response to the resource to use in a controller return statement. $model->sublinkRedirect('edit'); // Generates a redirect response to the resource's edit page to use in a controller return statement.