[英]Laravel REST API and frontend
我在 Laravel 中創建了一個小型數據庫項目,並在 Laravel 中添加了 REST API 以將移動應用程序與數據庫連接。 我應該使用什么來從 Web 應用程序中的數據庫獲取數據? 使用 Laravel 模型很容易,但這是創建另一個控制器來處理表單等而不是使用 rest api 控制器的好方法嗎? 謝謝
Laravel 也以自己的方式支持 Restful API。 為了這
php artisan make:controller Api/TestController
在routes/api.php
定義你的路由:
Route::group(['namespace' => 'Api'], function (){ Route::group(['prefix' => '/test'], function () { Route::get('/', 'TestController@list); Route::get('/single', 'TestController@single'); }); });
為作為集合數組的數據創建資源集合
php artisan make:resource Api/Collections TestCollection
此命令在文件夾app/Http/Resources/Api/Collections
創建一個集合,打開並更改toArray($request)
函數並添加一個函數with($request)
如下代碼:
public function toArray($request) { return $this->collection->map(function ($item){ return [ 'id' => $item->id, // $item is instance of Test model 'name' => $item->name, 'description' => $item->description, ]; }); } public function with($request) // optional : this method return with of response { return [ 'status' => true ]; }
所以去 TestController 並創建一個獲取所有測試的方法:
public function list() { $tests = Test::all(); // your Test Model return new TestCollection($test); // TestCollection you created above }
這是返回一個包含測試數組的 json 對象。
獲取單個測試: php artisan make:resource Api/Resources TestResource
然后轉到app/Http/Resources/Api/Collections
TestResource 並更改如下代碼:
public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, // $this is instance of Test model 'description' => $this->description, 'body' => $this->body, 'diff_name' => $this->name_in_table // you can change the name differ from name in model instance ]; }
所以去 TestController 並為單個測試創建一個方法
public function single(Request $request)
{
$test = Test::findOrFail($request->id);
return new TestResource($test);
}
這是 laravel 中 Rest API 的總結。 希望你覺得它有用
使用 laravel,您可以利用CreateFreshApiToken
中間件來重用您的 api 端點。
然后你只需要創建新的控制器和方法來顯示視圖。 所有 CRUD 的東西都可以重用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.