1 year ago

When is a JSON API necessary in a Laravel app?

Posted 1 year ago by trevorpan

When you type JSON API and Laravel into a search engine there's tons of posts on how to build one—even the virtues of building one. I could not find one that stated why, or when to use one. e.g. when your app does x, it "must" use a JSON API.

I watched the Laracasts API Resources video and it seems great, but I'm not fully understanding the difference of retrieving database info as JSON vs what a Controller will do (without ResourceCollections). this video shows data rendered as webpages (with styling), but also JSON info in the background if you use the right api web address. e.g.

I'm having a hard time figuring out if it's necessary in my app. Below is a attempt at using a ResourceCollection, after checking out Laravel Up and Running 2.0 v2 (book).


use App\Job;
use App\Http\Resources\Job as JobResource;

Route::get('jobs/{id}', function ($id){
             return new JobResource(Job::find($id));

The above spits out (without showing the website view):

    id   1
    jobtitle    "Test"
    body    "test"
    projectaddress  "123"
    city    "phoenix"
    state   "arizona"
    zipcode 85004
    biddertype  "subcontractor"
    job "materials"
    subjob  "mechanical"
    deadline"2019-05-13 16:26:58"

If a poster posted a job, and I wanted it to then be posted to say Twitter, or LinkedIn (for promotion), is it mandatory to use the JSON API resource method?

Can this feature be accomplished with just controllers?

Please sign in or create an account to participate in this conversation.