danielsundermeier/laravel-model-path

0.4.1 2021-03-06 09:24 UTC

This package is auto-updated.

Last update: 2024-09-06 17:08:08 UTC


README

Laravel模型知道自己的路由。

Model::indexPath(); // index, store

$model->index_path; // index, store
$model->create_path; // create
$model->path; // show, update, delete
$model->edit_path; // edit

安装

您可以通过Composer安装此包

composer require danielsundermeier/laravel-model-path

使用方法

基础知识

routes/web.php

Route::resource('movies', App\Http\Controllers\Movies\MovieController::class);

模型必须使用 HasModelPath 特性,并且有一个 const ROUTE_NAME

app/Models/Movie.php

use D15r\ModelPath\Traits\HasModelPath;

class Movie extends Model
{
    use HasFactory, HasModelPath;

    const ROUTE_NAME = 'movies';
}
Movie::indexPath(); // /movies

$movie = Movie::find(1);

$movie->index_path; // /movies
$movie->create_path; // /movies/create
$movie->path; // /movies/1
$movie->edit_path; // /movies/1/edit

高级

routes/web.php

Route::resource('{type}/{model}/watched', App\Http\Controllers\Watched\WatchedController::class);

app/Models/Watched.php

use D15r\ModelPath\Traits\HasModelPath;

class Watched extends Model
{
    use HasFactory, HasModelPath;

    const ROUTE_NAME = 'watched';

    public function getRouteParameterAttribute() : array
    {
        return [
            'type' => $this->watchable_type::ROUTE_NAME,
            'model' => $this->watchable_id,
            'watched' => $this->id,
        ];
    }
}
Watched::indexPath([
    'watchable_type' => Movie::class,
    'watchable_id' => 1
]); // /movies/1/watched

$watched = Watched::find(1);

$watched->index_path; // /movies/1/watched
$watched->create_path; // /movies/1/watched/create
$watched->path; // /movies/1/watched/1
$watched->edit_path; // /movies/1//watched/1/edit

贡献

贡献使开源社区成为一个如此美妙的地方,可以学习、启发和创造。您所做出的任何贡献都 非常感激

  1. 分支项目
  2. 创建您的功能分支 (git checkout -b feature/AmazingFeature)
  3. 提交您的更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开一个拉取请求