laravel如何基于route实现API/JSON形式的数据获取方法

在做SPA-APP的时候会需要很多api/json来进行数据通信获取消息,下面通过一个例子来讲解
1、第一步:在控制器文件夹中添加一个controller
<code>php artisan make:controller SearchController</code>
2、第二步:在route.php文件夹中
<code>Route::get('/api/v1/search','SearchController@ searchByName')</code>
3、第三步:编辑controller文件

class SearchController extend controller{
        private $clientInterface;
        public function _constructor(ComicClientInterface $clientInterface){
                this->clientInterface=$clientInterface;
        }
        puclic function searchByName(Request $request){
                try{
                      $name=$request->input('name');
                      $offest=$request->input('offest');
                      $result=this->clientInterface->comics($name,$offest);`
                      return Response::json(['data'=>$results['data'],'message'=>'success getting message'],200);
                }catch(\Exception  $e){
                       return Response::json(['data'=[],'message'=>'error getting message'],400)
                }
        }
}

最后可以得到这样的内容

api.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容