I wrote the code to fetch the JSON Data. For that I tried to do this in 2 projects.
- First Laravel project which has API code for database interaction only.
Sample code in API controller
class CountryAPI extends Controller
{
public function AllCountries() {
return response()->json(['CountryList' => \App\Models\CountryModel::all()]);
}
}
- Second Laravel project which is a Presentation Layer that has code to access data from an API. So, Database is not exposed directly in this layer, instead a URL is being used to access data.
Sample code in the Presentation Layer
class CountryController extends Controller {
public function AllCountries() {
$url = "http://localhost/API/public/Countries";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
return view('Country.List', array("Countries" => $json_data["CountryList"]));
}
}
Then inside the View it is like below.
@foreach($Countries as $Country)
<tr class="odd pointer">
<td class=" ">{{$Country["Country"]}}</td>
<td class=" ">{{$Country["CountryCode"]}}</td>
</tr>
@endforeach
This is just a beginning to learn how to isolate the database code from Presentation Layer.
Question: Is there problem in below points?
- Code Quality
- Approach to fetch data in Presentation layer from API.
- As website users will send request to website and then website will send request to Database server through an API. So each requests will have one in direct additional request. Is that good?
Reason I asked this because Data has to be accessed from Android as well as from Website
all()
you can add one function in country model asgetAllCountries()
which will return all countries. Now you can easily used this model in both ways as you have mentioned. \$\endgroup\$