Laravel REST API和前端
我在Laravel中创建了一个小数据库项目,并在Laravel中添加了RESTAPI,以将移动应用程序与数据库连接起来。在web应用程序中,我应该使用什么从数据库获取数据?使用laravel模型很容易,但这是创建另一个控制器来处理表单等而不是使用RESTAPI控制器的好方法吗?感谢使用laravel,您可以通过利用Laravel REST API和前端,laravel,rest,Laravel,Rest,我在Laravel中创建了一个小数据库项目,并在Laravel中添加了RESTAPI,以将移动应用程序与数据库连接起来。在web应用程序中,我应该使用什么从数据库获取数据?使用laravel模型很容易,但这是创建另一个控制器来处理表单等而不是使用RESTAPI控制器的好方法吗?感谢使用laravel,您可以通过利用 然后,您只需要创建新的控制器和方法来显示视图。所有的CRUD都可以重用。Laravel还以自己的方式支持Restful API。 为此 在Api文件夹中创建控制器:php arti
然后,您只需要创建新的控制器和方法来显示视图。所有的CRUD都可以重用。Laravel还以自己的方式支持Restful API。 为此
- 在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
函数,然后使用($request)添加一个函数,如以下代码所示:toArray($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 }
- 要获取单个测试,请执行以下操作:
然后转到php artisan make:Resources Api/Resources TestResource
中的TestResource,并更改如下代码:app/Http/Resources/Api/Collections
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 ]; }
public function single(Request $request)
{
$test = Test::findOrFail($request->id);
return new TestResource($test);
}
这是对laravel中RESTAPI的总结。希望你觉得有用