tomschlick/laravel-linkable

Laravel模型的URL绑定

v4.0 2021-07-15 18:07 UTC

This package is auto-updated.

Last update: 2024-09-18 08:01:22 UTC


README

StyleCI Build Status Latest Stable Version Total Downloads License

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.