dpftppc9674
2017-04-20 09:12
浏览 227
已采纳

如何在laravel中从内部api请求获取json响应?

My route file (routes/api.php) :

Route::group(['middleware'=>'cors', 'prefix'=>'v1/'], function(){
    Route::resource('users', 'UserController');
    Route::resource('products', 'ProductController');
    Route::resource('categories', 'CategoryController');

    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
    Route::get('authenticate/user', 'AuthenticateController@getAuthenticatedUser');
});

My ProductController file():

public function index(){
    $request = Request::create('api/v1/products/', 'GET');
    $instance = json_decode(Route::dispatch($request)->getContent());
    echo "<pre>"; print_r($instance); exit;

    return view('pages.users.my_sell', ['products'=>$products]); 
}

while i try to print the $instance variable i get the following error : enter image description here

i need to get all the object from the api and need to pass the objects to my blade.

图片转代码服务由CSDN问答提供 功能建议

我的路径文件(routes / api.php):

  Route :: group(['middleware'=&gt;'cors','prefix'=&gt;'v1 /'],function(){
 Route :: resource('users','UserController'); \  n Route :: resource('products','ProductController'); 
 Route :: resource('categories','CategoryController'); 
 
 Route :: resource('authenticate','AuthenticateController',[' 只有'=&gt; ['index']]); 
 Route :: post('authenticate','AuthenticateController @ authenticate'); 
 Route :: get('authenticate / user','AuthenticateController @ getAuthenticatedUser')  ; 
}); 
   
 
 

我的ProductController文件():

  public function index(){\  n $ request = Request :: create('api / v1 / products /','GET'); 
 $ instance = json_decode(Route :: dispatch($ request) - &gt; getContent()); 
 echo“  &LT;预&gt;“中; 的print_r($实例); 退出; 
 
返回视图('pages.users.my_sell',['products'=&gt; $ products]);  
} 
   
 
 

当我尝试打印$ instance变量时,我收到以下错误: < / p>

我需要从api获取所有对象,并且需要将对象传递给我的刀片。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsgwdigu84950 2017-04-20 09:54
    已采纳

    In your controller, have you included this?

    use \Illuminate\Support\Facades\Route;
    
    已采纳该答案
    打赏 评论
  • dsstjqsr631426 2017-04-20 09:15

    You're doing it wrong. If you do not want to repeat Eloquent code, just create a getAllPproducts() method in the model and use it in controller methods:

    public function index()
    {
        return view('pages.users.my_sell', [ 
            'products' => $this->product->getAllProducts()
        ]); 
    }
    

    Just an example of getAllProducts():

    public function getAllProducts()
    {
        return $this->paginate(20);
    }
    
    打赏 评论

相关推荐 更多相似问题