dandisy / elorest
使用laravel eloquent (方法和参数) 查询REST API服务器
Requires
- php: >=5.5.9
- dev-master
- 1.32.2
- 1.32.1
- 1.32.0
- 1.31.1
- 1.31.0
- 1.30.1
- 1.2.37
- 1.2.36
- 1.2.35
- 1.2.34
- 1.2.33
- 1.2.32
- 1.2.31
- 1.2.30
- 1.2.29
- 1.2.28
- 1.2.27
- 1.2.26
- 1.2.25
- 1.2.24
- 1.2.23
- 1.2.22
- 1.2.21
- 1.2.20
- 1.2.19
- 1.2.18
- 1.2.17
- 1.2.16
- 1.2.15
- 1.2.14
- 1.2.13
- 1.2.12
- 1.2.11
- 1.2.10
- 1.2.9
- 1.2.8
- 1.2.7
- 1.2.6
- 1.2.5
- 1.2.4
- 1.2.3
- 1.2.2
- 1.2.1
- 1.1.2
- 1.1.1
- 1.0.15
- 1.0.14
- 1.0.13
- 1.0.12
- 1.0.11
- 1.0.10
- 1.0.9
- 1.0.8
- 1.0.7
- 1.0.6
- 1.0.5
- 1.0.4
- 1.0.3
- 1.0.2
- 1.0.1
- 1.0.0
This package is auto-updated.
Last update: 2024-09-18 06:57:11 UTC
README
Laravel eloquent REST API包
使用它,我们可以使用laravel eloquent命令(方法和参数)查询restapi
借用laravel eloquent语法(方法及参数),包括laravel分页。
请查阅laravel的eloquent文档 https://laravel.net.cn/docs
示例查询
if the model namespace is "App\Models"
https://your-domain-name/api/elorest/Models/Post?leftJoin=comments,posts.id,comments.post_id&whereIn=category_id,[2,4,5]&select=*&get=
https://your-domain-name/api/elorest/Models/Post?join[]=authors,posts.id,authors.author_id&join[]=comments,posts.id,comments.post_id&whereIn=category_id,[2,4,5]&select=posts.*,authors.name as author_name,comments.title as comment_title&get=
https://your-domain-name/api/elorest/Models/Post?&with=author,comment&get=*
https://your-domain-name/api/elorest/Models/Post?&with=author(where=name,like,%dandisy%),comment&get=*
multiple first level of nested closure deep
https://your-domain-name/api/elorest/Models/Post?&with=author(where=name,like,%dandisy%)(where=nick,like,%dandisy%),comment&get=*
the second level of nested closure deep
https://your-domain-name/api/elorest/Models/Post?&with=author(with=city(where=name,like,%jakarta%)),comment&get=*
https://your-domain-name/api/elorest/Models/Post?&with[]=author(where=name,like,%dandisy%)&with[]=comment(where=title,like,%test%)&get=*
https://your-domain-name/api/elorest/Models/Post?paginate=10&page=1
if the model namespace only "App"
https://your-domain-name/api/elorest/User?paginate=10&page=1
for sortBy by related field
https://your-domain-name/api/elorest/Models/Post?&with=author(with=city(where=name,like,%jakarta%)),comment&get=*&sortBy=category.0.name
https://your-domain-name/api/elorest/Models/Post?&with=author(with=city(where=name,like,%jakarta%)),comment&get=*&sortByDesc=category.0.name
for select specific field/s in clousure of "with" command don't forget to include the foreign key to resolve the relationship, otherwise you'll get zero results for your relation
https:///gamify/public/api/elorest/Models/Character?with[]=categories.category&with[]=datasources(select=id,model_id,value)&with[]=user&get=*
upload file
https://your-domain-name/api/elorest/upload
whereHas for where query in related clousure
https:///online-shop/public/api/elorest/Models/Merchant?with[]=cartItems.product.category&with[]=cartItems(where=created_by,1)&whereHas=cartItems(where=created_by,1)&get=*
whereRaw
https:///online-shop/public/api/elorest/Models/Merchant?whereNotNull=label_id&whereRaw=find_in_set('3',label_id)&orWhereRaw=find_in_set('19',label_id)&get=*
安装
composer require dandisy/elorest
用法
将此(elorest路由)粘贴到您的laravel项目(routes/api.php)中
Elorest::routes();
or with middleware
Elorest::routes([
'middleware' => ['auth:api', 'throttle:60,1'],
// 'only' => ['post', 'put', 'patch', 'delete'],
'except' => ['get']
]);
异常处理
使用laravel错误处理器 (https://laravel.net.cn/docs/8.x/errors)
将异常处理器类发布到您的laravel webcore项目中
php artisan vendor:publish --provider="Dandisy\Elorest\ElorestServiceProvider" --force
身份验证
使用laravel passport (https://laravel.net.cn/docs/8.x/passport)
授权
使用laravel gates & policies (https://laravel.net.cn/docs/8.x/authorization)
为每个模型创建策略
php artisan make:policy PostPolicy --model=Post
注册策略
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Post::class => PostPolicy::class,
];
/**
* Register any application authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
或使用策略自动发现
use Illuminate\Support\Facades\Gate;
Gate::guessPolicyNamesUsing(function ($modelClass) {
// return policy class name...
});
模型
以防止某些字段被设置(用于忽略字段,而不是授权)
...
public static $elorestPreventSetOnCreate = [
'user_id', 'phone', 'id_card',
];
public static $elorestPreventSetOnUpdate = [
'user_id', 'id_card',
];
...
向“Elorest”中添加额外的逻辑,如果需要,请在此模型类中添加这些方法和属性
...
/**
* Elorest file fields
*
*/
public static elorestFileFields = [
'file_url', 'video_url'
]
/**
* Elorest before
*
* @param Request $request
*/
public function elorestBefore($request) {
// write your code here;
}
/**
* Elorest append
*
* @param Post $post
*/
public function elorestAppend($post) {
// write your code here;
}
/**
* Elorest after
*
* @param Request $request
* @param Post $post
*/
public function elorestAfter($request, $post) {
// write your code here;
}
...
策略
检查用户授权
$check = false; // false first
...
return $user->id && $check || $user->is_admin;
禁用隐藏字段
public function viewAny(User $user, Model $data)
{
...
if($user->id == $userId || $user->is_admin) {
$data->elorestDisableHiddenProperty = true;
}
...
}
可格式化的JSON响应(Beta)
请参阅sample/response_format.blade.php文件
文档
获取全部
https://your-domain-name/api/elorest/Models/Post
for
App\Models\Post::all();
按ID查找
https://your-domain-name/api/elorest/Models/Post/7
for
App\Models\Post::find(7);
获取Where和First
https://your-domain-name/api/elorest/Models/Author?where=name,like,%dandi setiyawan%&select=*&first=
for
App\Models\Author::where('name', 'like', '%dandi setiyawan%')->first();
获取Count(聚合)
https://your-domain-name/api/elorest/Models/Author?count=*
for
App\Models\Author::count();
获取Join(多联接)
https://your-domain-name/api/elorest/Models/User?join[]=contacts,users.id,contacts.user_id&join[]=orders,users.id,orders.user_id&select=users.*,contacts.phone as user_phone,orders.price as order_price&get=
for
App\Model\User::join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
获取WhereIn
https://your-domain-name/api/elorest/Models/Author?whereIn=id,[1,2,3]&get=*
for
App\Models\Author::whereNotIn('id', [1, 2, 3])
->get(*);
获取Multi With和Where(多嵌套闭包)
https://your-domain-name/api/elorest/Models/Post?&with=author(with=city(where=name,like,%jakarta%)),comment&get=*
for
App\Models\Post::with(['author' => function($query) {
$query->with(['city' => function($query) {
$query->where('name', 'like', %jakarta%)
}]);
}])
->with('comment')
->get(*);
按ID更新
var settings = {
"async": true,
"crossDomain": true,
"url": "https:///webcore/public/api/elorest/User/2",
"method": "PUT",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "833c6c7e-87f7-e527-e1ba-62a21aa39aff"
},
"processData": false,
"data": {votes: 1}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
更新Where(* 在laravel 10中,此功能将仅在无尾随 'get' 或 'first' 函数的情况下工作)
PUT /webcore/public/api/elorest/User?where=email,dandi@sgdigitals.com&select=*&first= HTTP/1.1
Host: localhost
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: fa3347b0-1f44-8622-a078-42b1369bbdd7
{
"votes": 1
}
or
var data = JSON.stringify({
"votes": 1
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("PUT", "https:///webcore/public/api/elorest/User?where=email,dandi@sgdigitals.com&select=*&first=");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "0ea7fa6a-b7d2-73e2-81e6-10ca983de686");
xhr.send(data);
for
App\Models\Author::where('email', 'dandi@sgdigitals.com')
->update(['votes' => 1]);
可扩展
- create your classes inherit or implement from the Elorest artifacts
- override or create new methods
- register your route
注意
add a public property "elorest = true or false" to the model class to enable or disable Elorest for that model
include the header Accept: application/json in the http request
for PUT/PATCH requests, use Content-type: application/x-www-form-urlencoded or application/json and for updating file, use POST with request body containing _method = PUT or PATCH
参考文献
- 201 New resource has been created successfully
- 400 Bad request (something wrong with URL or parameters)
- 401 Not authorized (not logged in)
- 403 Logged in but access to requested area is forbidden
- 404 Not Found (page or other resource doesn’t exist)
- 410 Resource not avalibale
- 422 Unprocessable Entity (validation failed)
- 500 General server error