来自两个laravel项目的API

I create two laravel projects. One is for backend connect with database and second project is for frontend. And then i create route API from projectone (backend project) get data from database and pass to json. and i want projecttwo(frontend) get the data from api url.

i try this code:

My API route in first project:

Route::get('test',function(){
    $response=DB::table('student_tbl')->select('title')->get();
    return response()->json($response,200);
});

My Secondproject:

$client = new \GuzzleHttp\Client();        
        // Create a request
        $request = $client->get('http://localhost/myfirstproject/public/api/test');
        // Get the actual response without headers
        $response = $request->getBody();
        $json_decode=json_decode($response,true);
        foreach ($json_decode as $key => $value) {
            echo $value['title'].'<br>';
        } 

Buti get 500 internal server error.

How to fixed this?

Try this to get the contents from your request. Since you are receiving the API response while you are trying from the browser, it seems there can be an issue with the second project.

You have to get the contents before passing the value for JSON decoding.

$response = $request->getBody()->getContents();

Base table or view not found means database was not found

Run migrations with

 php artisan migrate 

If you face other errros while running migrations then try this command

php artisan migrate:refresh

write your code in try catch like this:

try{

  $client = new \GuzzleHttp\Client();        
    // Create a request
    $request = $client->get('http://localhost/myfirstproject/public/api/test');
    // Get the actual response without headers
    $response = $request->getBody();
    $json_decode=json_decode($response,true);
    foreach ($json_decode as $key => $value) {
        echo $value['title'].'<br>';
    } 

 }catch(\Exception $e){

    \Log::error( $e->getMessage().' '. $e->getLine() .' '. $e->getFile());
    return $e->getMessage().' '. $e->getLine() .' '. $e->getFile(); 

 }

Also, open your browser's developer console and open the network tab. Refresh your page and find something matching to your route in network controller. It will be red since you are getting error. click on it and see what it says. If your don't understand then just paste that response in your question

Error code 500 basically means you have something wrong with your code. Try this turn one your application debug mode from .env if it is already there then its good.

Then try to hit the api from the browser check if that is giving /returning the response as expected. If that does then something is wrong with your 2ned project. Try to debug it same way .

The laravel error will give you a good hint where it is going wrong.

https://github.com/laravel/framework/issues/19454#issuecomment-305955056

based on the comment, you need to run php artisan config:cache to save the config for project