cliffordjames/laravel-urls

Eloquent 模型 URL 特性

1.0.4 2017-09-14 06:53 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:25:55 UTC


README

此包允许您为 Eloquent 模型创建简单的路由。

安装

$ composer require cliffordjames/laravel-urls

使用

假设您有以下路由来显示用户

Route::get('/users/{user}', function (\App\User $user) {
    return $user;
})->name('users.show');

您只需将特性添加到 User 模型中

<?php

namespace App;

use CliffordJames\LaravelUrls\HasUrl;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable, HasUrl;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

然后您可以使用特性的 url() 函数生成此路由的 URL

$user = User::first();
//
$user->url(); // -> /users/1
// vs
route('users.show', $user); // -> /users/1

资源路由

您可以在 url() 函数中将路由名称指定为第一个参数

Route::resource('users', 'UserController');

$user = User::first();

$user->url(); // -> /users/1
$user->url('show'); // -> /users/1
$user->url('edit'); // -> /users/1/edit
$user->url('update'); // -> /users/1
...

附加参数

假设您有以下路由

Route::get('/threads/{channel}/{thread}', 'ThreadsController@show')->name('threads.show');

并且您已添加特性并将 Thread 模型与 Channel 模型的关系设置为,以下示例具有相同的结果

$thread->url(); // -> /threads/*channel_id*/*thread_id*
$thread->url($thread->channel); // same as above
$thread->url($thread, $thread->channel); // same as above
$thread->url([$thread, $thread->channel]); // same as above
$thread->url(['thread' => $thread, 'channel' => $thread->channel]); // same as above

route('threads.show', ['thread' => $thread, 'channel' => $thread->channel]); // same as above

配置

目前您可以进行的配置只有一个,那就是在模型本身上设置 $baseRoute,它默认为生成模型表名的方法相同。

例如 User 模型,如果没有设置,则默认为 user

protected $baseRoute = 'profile';

现在 $user->url() 正在寻找 profile.show 路由。