jameslkingsley / laravel-references
内置模型引用。
dev-master
2017-10-06 16:48 UTC
Requires
- php: ^7.1
- illuminate/database: ^5.5
- illuminate/http: ^5.5
- illuminate/routing: ^5.5
- illuminate/support: ^5.5
Requires (Dev)
- orchestra/testbench: ^3.5
- phpunit/phpunit: ^6.3
This package is auto-updated.
Last update: 2024-09-09 21:15:22 UTC
README
此Laravel >=5.5的包提供了一种快速简单的方法,可以将唯一的引用添加到模型中,这些引用可以通过路由模型绑定来解析。你通常不想将你的主键暴露给客户端,如果没有像用户名或缩略名这样的唯一引用,你就无法快速构建RESTful API。使用此包,你可以给你的模型提供一个唯一引用,并立即开始在路由中使用它。
以下是一些你可以做的事情的简要示例
// Simply add the binding to your route Route::get('/api/customers/{ref}', function (Customer $customer) { // }); // Then just use the model's reference in your request GET /api/customers/cus_tKCulsB67hty
安装
您可以使用以下命令通过composer安装此包
composer require jameslkingsley/laravel-references
如果您使用的是Laravel 5.5或更高版本,此包将自动发现,但是如果您使用的是低于5.5的任何版本,您需要按老方法注册它
接下来,您必须在config/app.php
中安装服务提供者
'providers' => [ ... Kingsley\References\ReferencesServiceProvider::class, ];
现在发布配置
php artisan vendor:publish --provider="Kingsley\References\ReferencesServiceProvider"
这是已发布的配置文件的 内容
return [ /* * Name of the database table that * will store model references. */ 'table_name' => 'references', /* * Name of the route model binding. * Eg. /api/customers/{ref} */ 'binding_name' => 'ref', /* * Whether the reference hash should * prefix the shortened model type. * Eg. App\Customer -> cus_tKCulsB67hty */ 'prefix' => false, ];
现在只需运行迁移!
php artisan migrate
使用方法
选择您想要使其可引用的模型。在这个例子中,我会选择Customer
。我们将导入特性并在类中使用它。
namespace App; use Kingsley\References\Referenceable; use Illuminate\Database\Eloquent\Model; class Customer extends Model { use Referenceable; }
现在设置您的路由以使用绑定。无论您使用控制器还是匿名函数,只需在参数中对模型类进行类型提示即可解析引用。
Route::get('/api/customer/{ref}', function (Customer $customer) { return $customer; });
当从客户端提交AJAX请求时,您可以使用附加到模型上的ref
属性。
ajax.get(`/api/customer/${customer.ref}`);
前缀
如果您想要为引用添加前缀,只需在配置中将prefix
选项设置为true
。默认情况下,它将使用类基本名的第一个三个字符。
App\Customer -> cus_tKCulsB67hty
或者,您可以通过设置以下内容显式地为模型设置前缀。请注意,如果您将其设置为null
,则即使您的prefix
配置选项设置为true
,它也不会有前缀。
class Customer extends Model { use Referenceable; protected $referencePrefix = 'customer'; }