<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dean Tedesco on Medium]]></title>
        <description><![CDATA[Stories by Dean Tedesco on Medium]]></description>
        <link>https://medium.com/@dinotedesco?source=rss-e2349cc70091------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c3v_HRX_Z7qkgiqy.jpg</url>
            <title>Stories by Dean Tedesco on Medium</title>
            <link>https://medium.com/@dinotedesco?source=rss-e2349cc70091------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:27:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dinotedesco/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamic Environment for create-react-app]]></title>
            <link>https://medium.com/@dinotedesco/dynamic-environment-for-create-react-app-b45f047640b?source=rss-e2349cc70091------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45f047640b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[dynamic-environment]]></category>
            <category><![CDATA[12-factor-app]]></category>
            <dc:creator><![CDATA[Dean Tedesco]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 06:49:21 GMT</pubDate>
            <atom:updated>2019-04-16T06:58:59.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript: Dynamic Environments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*SUShbemvlsjRL8jcFiG8NA.png" /></figure><h3>The Problem</h3><p>When building your create-react-app for production deployments you currently need to bake in any environment variables at build time. This method of building your application can cause some issues particularly if you have many environments/stages in your deployment processes as you have to build for each one.</p><p>Some issues for example are:</p><ul><li>You can’t build once and deploy everywhere</li><li>If you need to change your environment after deployment for any reason you have to perform another build</li><li>Your environment is controlled by your build as opposed to your runtime</li></ul><p>Some cons to this approach:</p><ul><li>You must make sure you have all the correct environment variables set up on your deployment systems available otherwise your built apps will fail</li><li>Maintaining your application’s environment falls into the domain of DevOps</li></ul><h3>The Solution</h3><p>Convert any process.env.* calls in your code to window._env_.* to access your environment at boot time instead of converting them at build time.</p><blockquote>NOTE: this will not help you if you are deploying your built application on a CDN where you can’t set environment variables.</blockquote><p>To help achieve this goal I’ve just published a new NPM package which we are going to start using at my work and you can find it at <a href="https://www.npmjs.com/package/@ethical-jobs/dynamic-env">https://www.npmjs.com/package/@ethical-jobs/dynamic-env</a>.</p><p>I’d love any feedback and/or pull requests as I think this could be very useful for many developers out there.</p><p>Github Repo: <a href="https://github.com/ethical-jobs/dynamic-env">https://github.com/ethical-jobs/dynamic-env</a></p><h3>Kudos</h3><p>I also have to give kudos to <a href="https://medium.com/u/4e82efa9b1fb">Krunoslav Banovac</a> for his inspiration as this package was based on his blog article <a href="https://medium.freecodecamp.org/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70">https://medium.freecodecamp.org/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45f047640b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel API Resources — What if you want to manipulate your models before transformation?]]></title>
            <link>https://medium.com/@dinotedesco/laravel-api-resources-what-if-you-want-to-manipulate-your-models-before-transformation-8982846ad22c?source=rss-e2349cc70091------2</link>
            <guid isPermaLink="false">https://medium.com/p/8982846ad22c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-resources]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Dean Tedesco]]></dc:creator>
            <pubDate>Tue, 13 Feb 2018 06:48:06 GMT</pubDate>
            <atom:updated>2018-02-13T06:48:06.725Z</atom:updated>
            <content:encoded><![CDATA[<p>So, I recently came across this issue when showing a colleague how awesome Laravel’s API Resources are. It turns out that passing external attributes down to a resource collection’s children doesn’t happen automatically like I first thought. And then I realised that Resources aren’t magic! Why did I think they were magic? There is nothing in the documentation to suggest this. I just assumed like so many other features of Laravel that if you created a UserResource and a UserCollection that the UserCollection would automatically understand that the UserResource was the singular of the collection and would automatically transform the User model into a UserResource even though you pass in a collection of User models to the UserCollection resource. Make sense, easy, right? Well, it doesn’t work like that. API Resources are just there to do what you tell them to do, which makes them very powerful IMHO.</p><h4>So, if there is no magic then how do they work?</h4><p>Essentially they are just simple objects with one very important job to do — transform your objects (interesting I said objects and not models). To do this out of the box, all you have to do is instantiate the Resource (collection or individual) with an Arrayable object. If you did nothing else but generate a standard Resource and pass in an Arrayable object the Resource would transform that object automatically, and because Models are Arrayable this is where I got caught out because if you create a resource collection and instantiate it with a collection of models then the models get toArray&#39;d and not their corresponding resource.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers\Api;<br><br><strong>use </strong>App\Http\Resources\UserCollection;<br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Request;<br><strong>use </strong>App\Http\Controllers\Controller;<br><br><strong>class </strong>UserController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * List all users.<br>     * <br>     * </em><strong><em>@param </em></strong><em>Request $request<br>     * </em><strong><em>@return </em></strong><em>UserCollection<br>     */<br>    </em><strong>public function </strong>index(Request $request)<br>    {<br>        $users = User::<em>all</em>();<br><br>        <strong>return new </strong>UserCollection($users);<br>    }<br>}</pre><p>This will just toArray()the models never hitting the UserResource at all.</p><h4>Ok, if the resource collection doesn’t automagically convert the model into the corresponding resource what do we do?</h4><p>We transform the collection of models into a collection of resources. Easy! Yes? Well it’s easier than you think. We could do this in the controller with something like this;</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers\Api;<br><br><strong>use </strong>App\Http\Controllers\Controller;<br><strong>use </strong>App\Http\Resources\UserCollection;<br><strong>use </strong>App\Http\Resources\UserResource;<br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Request;<br><br><strong>class </strong>UserController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * List all users.<br>     *<br>     * </em><strong><em>@param </em></strong><em>Request $request<br>     * </em><strong><em>@return </em></strong><em>UserCollection<br>     */<br>    </em><strong>public function </strong>index(Request $request)<br>    {<br>        $users = User::<em>all</em>();<br><br>        $users-&gt;transform(<strong>function </strong>(User $user) {<br>            <strong>return </strong>(<strong>new </strong>UserResource($user));<br>        });<br><br>        <strong>return new </strong>UserCollection($users);<br>    }<br>}</pre><p>This is perfectly acceptable, but it’s not very clean and we are already clogging up our controller with stuff it just shouldn’t care about. So where can we move this to? Well, how about the UserCollection::toArray() method?</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Resources;<br><br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Resources\Json\ResourceCollection;<br><br><strong>class </strong>UserCollection <strong>extends </strong>ResourceCollection<br>{<br>    <em>/**<br>     * Transform the resource collection into an array.<br>     *<br>     * </em><strong><em>@param  </em></strong><em>\Illuminate\Http\Request  $request<br>     * </em><strong><em>@return </em></strong><em>array<br>     */<br>    </em><strong>public function </strong>toArray($request)<br>    {<br>        $this-&gt;collection-&gt;transform(<strong>function </strong>(User $user) {<br>            <strong>return </strong>(<strong>new </strong>UserResource($user));<br>        });<br><br>        <strong>return parent</strong>::<em>toArray</em>($request);<br>    }<br>}</pre><p>And revert our controller back to the original;</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers\Api;<br><br><strong>use </strong>App\Http\Controllers\Controller;<br><strong>use </strong>App\Http\Resources\UserCollection;<br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Request;<br><br><strong>class </strong>UserController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * List all users.<br>     *<br>     * </em><strong><em>@param </em></strong><em>Request $request<br>     * </em><strong><em>@return </em></strong><em>UserCollection<br>     */<br>    </em><strong>public function </strong>index(Request $request)<br>    {<br>        $users = User::<em>all</em>();<br><br>        <strong>return new </strong>UserCollection($users);<br>    }<br>}</pre><p>Much nicer. We only care about creating a collection of UserResources when we are dealing with a UserCollection so this nicely encapsulates our code.</p><h4>Ok, but aren’t you missing the point of this article, Dean? How do we pass meta information from the collection to it’s children?</h4><p>Yes, yes, I’m getting to that.</p><p>So, scenario is that you want to transform your collection of users into a nice JSON API for the world to see. We have that now, but we also want to manipulate the JSON output for the individual UserResource based on some global value. How can we do this?</p><p>As an example say each user has a Bitcoin worth (yeah I work for a Crypto company now so this seems appropriate), so we might have a UserResource that looks like this;</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Resources;<br><br><strong>use </strong>Illuminate\Http\Resources\Json\Resource;<br><br><strong>class </strong>UserResource <strong>extends </strong>Resource<br>{<br>    <em>/**<br>     * Transform the resource into an array.<br>     *<br>     * </em><strong><em>@param  </em></strong><em>\Illuminate\Http\Request $request<br>     * </em><strong><em>@return </em></strong><em>array<br>     */<br>    </em><strong>public function </strong>toArray($request)<br>    {<br>        <strong>return </strong>[<br>            &#39;name&#39; =&gt; $this-&gt;name,<br>            &#39;username&#39; =&gt; $this-&gt;username,<br>            &#39;bitcoin&#39; =&gt; $this-&gt;bitcoin,<br>        ];<br>    }<br>}</pre><p>But what if we wanted to automatically convert the bitcoin value to USD or AUD for instance. Yeah we could do that on the model itself, but that would defeat the purpose of this article. We want to pass the convertTo meta data from the controller all the way down to the individual resource. Well Taylor to the rescue once again, all we need to do is set the additional property on the top most resource and we can do that like this;</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Controllers\Api;<br><br><strong>use </strong>App\Http\Controllers\Controller;<br><strong>use </strong>App\Http\Resources\UserCollection;<br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Request;<br><br><strong>class </strong>UserController <strong>extends </strong>Controller<br>{<br>    <em>/**<br>     * List all users.<br>     *<br>     * </em><strong><em>@param </em></strong><em>Request $request<br>     * </em><strong><em>@return </em></strong><em>UserCollection<br>     */<br>    </em><strong>public function </strong>index(Request $request)<br>    {<br>        $users = User::<em>all</em>();<br><br>        <strong>return </strong>(<strong>new </strong>UserCollection($users))-&gt;additional([<br>            &#39;meta&#39; =&gt; [<br>                &#39;convertCryptoTo&#39; =&gt; &#39;AUD&#39;<br>            ]<br>        ]);<br>    }<br>}</pre><p>The nice thing about this is that we get this automatically added to the top most resource as meta information in our JSON output. NICE!</p><p>So now that our UserCollection has this useful additional meta info how do we get it to our UserResource. Well that is easy because the UserCollection extends the ResourceCollection which in turn extends the Resource class which has the attributes property, making it available to both ResourceCollections and Resources. Awesome, we can just set the attributes on the UserResource then with the ones on the UserCollection.</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Resources;<br><br><strong>use </strong>App\User;<br><strong>use </strong>Illuminate\Http\Resources\Json\ResourceCollection;<br><br><strong>class </strong>UserCollection <strong>extends </strong>ResourceCollection<br>{<br>    <em>/**<br>     * Transform the resource collection into an array.<br>     *<br>     * </em><strong><em>@param  </em></strong><em>\Illuminate\Http\Request $request<br>     * </em><strong><em>@return </em></strong><em>array<br>     */<br>    </em><strong>public function </strong>toArray($request)<br>    {<br>        $this-&gt;collection-&gt;transform(<strong>function </strong>(User $user) {<br>            <strong>return </strong>(<strong>new </strong>UserResource($user))-&gt;additional($this-&gt;additional);<br>        });<br><br>        <strong>return parent</strong>::<em>toArray</em>($request);<br>    }<br>}</pre><p>Wow that was easy, last thing to do is actually do the conversion on our UserResource. Easy peasy!</p><pre><strong>&lt;?php<br><br>namespace </strong>App\Http\Resources;<br><br><strong>use </strong>Illuminate\Http\Resources\Json\Resource;<br><br><strong>class </strong>UserResource <strong>extends </strong>Resource<br>{<br>    <em>/**<br>     * Transform the resource into an array.<br>     *<br>     * </em><strong><em>@param  </em></strong><em>\Illuminate\Http\Request $request<br>     * </em><strong><em>@return </em></strong><em>array<br>     */<br>    </em><strong>public function </strong>toArray($request)<br>    {<br>        $convertTo = $this-&gt;attributes[&#39;meta&#39;][&#39;convertTo&#39;];<br><br>        <strong>return </strong>[<br>            &#39;name&#39; =&gt; $this-&gt;name,<br>            &#39;username&#39; =&gt; $this-&gt;username,<br>            &#39;bitcoin&#39; =&gt; $this-&gt;bitcoin,<br>            &#39;conversion&#39; =&gt; $this-&gt;convertTo($convertTo, $this-&gt;bitcoin)<br>        ];<br>    }<br><br>    <strong>private function </strong>convertTo($convertTo, $bitcoin)<br>    {<br>        <strong>return </strong>...<br>    }<br>}</pre><p>And that’s it. I’ll let you figure out how to convert Bitcoin into Fiat as I’m just too lazy.</p><p>Anyway, your response to this should look something similar to this;</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Dean Tedesco&quot;,<br>      &quot;username&quot;: &quot;developerdino&quot;,<br>      &quot;bitcoin&quot;: 100,<br>      &quot;conversion&quot;: 1000000<br>    }<br>  ],<br>  &quot;meta&quot;: {<br>    &quot;convertTo&quot;: &quot;AUD&quot;<br>  }<br>}</pre><p>Nice ha! I thought so.</p><p>By the way that Bitcoin is totally fictitious, I wish I had 100 BTC.</p><p>Hope you found this useful. If you did check out my other article on Laravel API Resources — <a href="https://medium.com/@dinotedesco/using-laravel-5-5-resources-to-create-your-own-json-api-formatted-api-2c6af5e4d0e8">Using Laravel 5.5 Resources to create your own {JSON:API} formatted API</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8982846ad22c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Laravel 5.5 Resources to create your own {JSON:API} formatted API]]></title>
            <link>https://medium.com/zero-equals-false/using-laravel-5-5-resources-to-create-your-own-json-api-formatted-api-2c6af5e4d0e8?source=rss-e2349cc70091------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6af5e4d0e8</guid>
            <category><![CDATA[laravel-5]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[json-api]]></category>
            <category><![CDATA[api-transformer]]></category>
            <dc:creator><![CDATA[Dean Tedesco]]></dc:creator>
            <pubDate>Thu, 07 Sep 2017 06:35:55 GMT</pubDate>
            <atom:updated>2020-01-12T23:55:02.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*y5_uGkNdD6h6pN2aU1RPGw.png" /></figure><p>Ever since I started writing APIs in Laravel I have been using the awesome <a href="http://fractal.thephpleague.com/">Fractal</a> package from <a href="https://thephpleague.com/">The League of Extraordinary Packages</a> and it has served its purpose exceptionally well for transforming raw models into JSON:API and other serialising methods, and until now it was really the only option.</p><h3>Introducing Laravel 5.5 Resource Classes</h3><p>We now have Resource classes we can use for our APIs out of the box in Laravel 5.5 without having to install any 3rd party packages.</p><h3>What are Resource Classes and why should I use it?</h3><p>A Resource class is a way to transform data from one format to another. Simply put, if we have a Article model and we want to manipulate the data or remove certain fields from the model before sending that in our response, it is difficult to do so by just responding with;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b00cfc1dd818271933d9d161dbf05aa/href">https://medium.com/media/2b00cfc1dd818271933d9d161dbf05aa/href</a></iframe><p>Granted this will give you a valid response, maybe something like this;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd1b2dac6c0e9f0e6b67d955d08905aa/href">https://medium.com/media/fd1b2dac6c0e9f0e6b67d955d08905aa/href</a></iframe><p>But what if you wanted to format your responses to a standard like JSON:API or any one of the other numerous standards out there. We would need to override the Model’s toArray implementation and now we are breaking the single responsibility rule. Why should the model care how to format a response to the end user? It shouldn’t! and this is where we can now utilise Resource classes in Laravel 5.5. Instead of doing what we did above we can now create a Laravel Resource using artisan and transform our model in any way we like.</p><p>For the rest of this article I’m going to show you how to utilise Laravel’s new Resource classes to implement the example on the <a href="http://jsonapi.org/">JSON:API specification home page</a>, which looks something like this;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e46eec0480ffa5fae567643594d8514/href">https://medium.com/media/3e46eec0480ffa5fae567643594d8514/href</a></iframe><h3>Create our Laravel Application</h3><p>First things first we need a test app to work with;</p><pre>laravel new articles-api</pre><p>Bear with me as I’ll try to fly through the boring setup parts as fast as possible. I’m also going to assume you know how to connect to a database and setup your environment, etc so that I won’t have to go through that in this article.</p><p>Continuing…</p><h3>Generate our database and models</h3><p>First things first we need some data so lets make some migrations.</p><pre>php artisan make:model People -mf<br>php artisan make:model Article -crmf<br>php artisan make:model Comment -mf</pre><p>As this is a tutorial we don’t want to waste time on the boring stuff so this command creates the model, resource controller (cr), migration (m) and factory (f) all in one go. Woohoo!</p><p>Lets fill these up with some boiler plate so we can get to the good stuff.</p><p>Open your migration files and add;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd21b0e3efc9e31f408f1423e80191f0/href">https://medium.com/media/bd21b0e3efc9e31f408f1423e80191f0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e6d570048c3eaac030d5b5c3133be0/href">https://medium.com/media/20e6d570048c3eaac030d5b5c3133be0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8da1c6a39ab47ea3fca100bb29f7f97/href">https://medium.com/media/b8da1c6a39ab47ea3fca100bb29f7f97/href</a></iframe><p>Now that you have the migrations lets migrate;</p><pre>php artisan migrate</pre><p>You also have <em>factory</em> classes available to seed some test data but I’ll leave that up to you to fill in the blanks for those.</p><h3>Building our JSON:API using Resource Classes</h3><p>Now that we have our database and presumably you have seeded your tables with some fake data we can move on to the fun stuff and what you really came here for.</p><h4>A bit of Theory First</h4><p>When dealing with resources and how to transform them into responses for the client we basically have 2 types, an <em>item</em> and a <em>collection. </em>An item resource as you might have guessed is basically a one to one representation of our model where as a <em>collection</em> is the representation of many <em>items. Collections </em>may also have meta data and other navigation information as well.</p><p>In terms of JSON:API we can represent an <em>item</em> like this;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7d6c0d6ccee3d0404fab1a2a639666/href">https://medium.com/media/fe7d6c0d6ccee3d0404fab1a2a639666/href</a></iframe><p>Whereas a <em>collection</em> would be represented like this (in it’s basic form);</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae04568b5b48fe71ca2b6e43d1dffe0d/href">https://medium.com/media/ae04568b5b48fe71ca2b6e43d1dffe0d/href</a></iframe><p>Now that we know the difference between an <em>item</em> and a <em>collection</em> lets try to replicate these using <em>Resource</em> classes.</p><p>First we need to generate 2 classes one to handle the <em>item</em> and the other to handle the <em>collection</em>. Luckily we can utilise artisan to do this.</p><pre>php artisan make:resource ArticleResource<br>php artisan make:resource ArticlesResource --collection</pre><p>You will now have a new directory under app/Http/Resources where all these resources will reside.</p><p>In each one of these classes you will have a toArray method which is where we will transform our models the way we want them. So lets change the App\Http\Resource\ArticleResource so it transforms our Article model into a JSON:API resource;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2751b0af51ee26519201ab0b9ecfadb6/href">https://medium.com/media/2751b0af51ee26519201ab0b9ecfadb6/href</a></iframe><p>As you can see we have top level type, id and attributes keys to start with. We’ll expand on this to include links and relationships as well in a bit but first lets create our controller and routes so we can see this in action.</p><pre>php artisan make:controller --resource ArticleController</pre><p>This will give us a resource based controller to start putting our RESTful API together. Now we need to tell our controller actions to use our newly created resource in the show method so lets add that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a892cc740e2d92660dde57d151d1821e/href">https://medium.com/media/a892cc740e2d92660dde57d151d1821e/href</a></iframe><p>And the route;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53824b205e3a98c4e3a3357557c8118f/href">https://medium.com/media/53824b205e3a98c4e3a3357557c8118f/href</a></iframe><p>For simplicity we can just use a resource based route entry here, we’ll be adding to it a bit so it not totally wasted.</p><p>So now you should have a fully operational API which can show an article resource by going to the /api/articles/{id} you should get a response back like this;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e10b1f81d5cfc614d972b6d4329420a1/href">https://medium.com/media/e10b1f81d5cfc614d972b6d4329420a1/href</a></iframe><p>Obviously you’ll need to add some data to your database and serve the API <em>— HINT:</em> php artisan serve then go to <a href="http://127.0.0.1/api/articles/1">http://127.0.0.1/api/articles/1</a> in Postman watch the magic.</p><h4>Making this JSON:API compliant</h4><p>All this is great and out of the box works a treat, but this article is about making use of the Resource classes to generate JSON:API compliant. To this the item shouldn’t have the data top level key. Well Laravel makes this easy we just need to tell the resource we don’t want it wrapped, so before calling the resource we need to call the static method withoutWrapping(), easy;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f81c679e19f649bb82d0e4f196d259e8/href">https://medium.com/media/f81c679e19f649bb82d0e4f196d259e8/href</a></iframe><p>Now you’ll get this when you call that endpoint;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d74df50d5388e11ac337fb8d97ff110a/href">https://medium.com/media/d74df50d5388e11ac337fb8d97ff110a/href</a></iframe><p>Awesome that was easy. Ok, so now lets add some more of the JSON:API goodness like links and relationships. Open up ArticleResource and lets add them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33184e8acbd8c59ec37d1365cef35fa/href">https://medium.com/media/d33184e8acbd8c59ec37d1365cef35fa/href</a></iframe><p>So pretty easy right we’ve added our article relationships and links. The self link will work out of the box because we added a route resource before to the controller so it knows how to resolve this route but we also have a new resource for our relationships which will need to be created. Easy, artisan to the rescue;</p><pre>php artisan make:resource ArticleRelationshipResource</pre><p>And just for expedience we’ll also create the rest of our resources now so we don’t have to later.</p><pre>php artisan make:resource AuthorIdentifierResource<br>php artisan make:resource CommentIdentifierResource<br>php artisan make:resource --collection ArticleCommentsRelationshipResource<br>php artisan make:resource --collection ArticlesResource </pre><p>We’ll pass $this to our ArticleRelationshipResource so we have access to the Article model and it’s relationships.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8274fe81595e9283da39589bab03d1c/href">https://medium.com/media/b8274fe81595e9283da39589bab03d1c/href</a></iframe><p>Notice in this class we have a new method with which is used to add meta data to our resources. This is handy to split out all non entity based data out from your resource.</p><p>So we’ve handled links and relationships now and we are pretty much done generating an item resource. I’ll let you work out the other resources and the data that needs to go in them (hint: it’s on github — link at the end of the article).</p><h3>Collection Resources</h3><p>Last thing to do is the collection resource, well this couldn’t be any easier. Lets open up our ArticleController and do this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/486a6770a25d641f983de5482b88e96f/href">https://medium.com/media/486a6770a25d641f983de5482b88e96f/href</a></iframe><p>So just like the show method we just return the resource and pass the collection of articles to it in it’s constructor. In this case we want to get a paginated list of Articles and eager load the relationships we want. Our ArticlesResource looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca8da27d6c24eddadaeb6577da936339/href">https://medium.com/media/ca8da27d6c24eddadaeb6577da936339/href</a></iframe><p>How easy is that, we are just using the ArticleResource which we have already done all the heavy lifting with and utilising the static collection method passing the paginated articles collection from the controller to be transformed.</p><h4>Included entities</h4><p>This is pretty good but we are still missing one part of our JSON:API resource and that is the unique list of included entities. So let’s add those now;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c226e32c7ab1d1e988f4a490e5848fb5/href">https://medium.com/media/c226e32c7ab1d1e988f4a490e5848fb5/href</a></iframe><p>Now you can see the reason we eager loaded the relationships in the controller. For JSON:API to be truely slim in it’s output we need a unique list of all related resources which can be referenced by the resource identifiers, aka &quot;data&quot;: {&quot;type&quot;: &quot;people&quot;, &quot;id&quot;: &quot;9&quot;}.</p><p>It turns out this is fairly straight forward to do with the Collection flatMap and map callback methods. flatMap is needed for collection relationships and map is need to item relationships. These will return collections of our relationships for all entities in our collection, so in this case we have multiple articles with authors and comments. We get new collections of all authors and comments for all articles and then merge them and make them unique.</p><p>Once we have a unique list of all relationships we need to get the corresponding resource class and instantiate that with our include. We just return this new collection of resources back and assign it to the included key and we are done. You should expect your api to output something along the lines of;</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89dabfc7e93080483ed5ac87560b20f3/href">https://medium.com/media/89dabfc7e93080483ed5ac87560b20f3/href</a></iframe><p>So now you can see the list of unique included resources which relate to all our articles.</p><h3>Conclusion</h3><p>I’ve tried to show how to use Laravel 5.5 Resources to create JSON:API compliant responses and it is surprisingly easy once you understand the basics of how they work.</p><p>I’ve also not included all the code in this article to actually make this application work if you are following along with the code as it would hae made the article very repetitive and boring (hopefully it isn’t boring already). If you want to explore these resources more you can checkout the the repo at github.com which is a fully working app and please if you see any issues or find a better way to handle the included data submit a PR and I’ll consider it or at least discuss it with you.</p><p><a href="https://github.com/developerdino/example-articles-api">developerdino/example-articles-api</a></p><p>I hope you found this informative and start making use of Laravel’s new resources in 5.5.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6af5e4d0e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zero-equals-false/using-laravel-5-5-resources-to-create-your-own-json-api-formatted-api-2c6af5e4d0e8">Using Laravel 5.5 Resources to create your own {JSON:API} formatted API</a> was originally published in <a href="https://medium.com/zero-equals-false">Zero Equals False</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>