<?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 Josh Thackeray on Medium]]></title>
        <description><![CDATA[Stories by Josh Thackeray on Medium]]></description>
        <link>https://medium.com/@josh_26582?source=rss-1d667445295c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*abo4g7E8yl2zAeIbvrAA1w.jpeg</url>
            <title>Stories by Josh Thackeray on Medium</title>
            <link>https://medium.com/@josh_26582?source=rss-1d667445295c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:59:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josh_26582/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[Tips for writing clean code in Laravel]]></title>
            <link>https://medium.com/@josh_26582/tips-for-writing-clean-code-in-laravel-5f5a4366169c?source=rss-1d667445295c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5a4366169c</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Josh Thackeray]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 13:24:44 GMT</pubDate>
            <atom:updated>2021-12-18T07:16:56.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*mOfb6cjav3OY5EdA.png" /></figure><p>As developers, one thing we are known to be good at is problem solving. Whether small, big, simple or complex… every line of code written or every program built has solved one or two problems.</p><p>According to <a href="https://www.statista.com/statistics/627312/worldwide-developer-population/">statista.com</a>, there were 23.9 million developers in the world back in 2019 and is expected to grow to 28.7 million by the end of 2024, that’s a growth of just over 20%. That’ll cover 0.3% of the entire population, and with all these developers comes just as many new ways of thinking when it comes to solving problems.</p><p>I’ve been a developer now for just over 6 years, specifically a web developer working in PHP with <a href="https://laravel.com/">Laravel</a> and I thought I’d share 4 of my most commonly used (best)-practices on a daily basis.</p><p><strong>Why Laravel?</strong> I’ll start by saying a common theory in the industry is that PHP is a dead language, however this can’t be true if 37% of all websites on the internet are Wordpress based which in turn is built with PHP. It may not be the best out there or the fastest but it’s definitely getting faster with the 8.x or even 7.x versions compared to its previous 5.x versions a couple of years ago.</p><p>PHP can be an easy language to get into and with Laravel just makes it that much simpler to write beautiful, well structured and easy to read code. Using it’s eloquent ORM, it’s even easier to interact with the database.</p><p>So this comes onto my key patterns I tend to follow when building applications:</p><h3><strong>Controller Requests</strong></h3><p>Request classes are nothing new in Laravel, in fact they’ve been around since version 5.0 back in February 2015 and they have been left fairly untouched since. But the principle here remains the same and is just as good a tool to utilise.</p><p>The reason this is on my list is being able to effectively use these in what I feel is the best way, being able to use a single request class for more than 1 route/method in a controller.</p><p>Think of creating a new blog post, we’d have 2 routes here; a GET for showing the form and a POST for storing the submission in the database. Now we can do this like so:</p><p><strong>BlogController.php</strong></p><pre><em>/**<br> * Shows the form for creating a new blog.<br> *<br> * </em><strong><em>@param </em></strong><em>Request $request<br> * </em><strong><em>@return </em></strong><em>Application|Factory|View<br> * </em><strong><em>@throws </em></strong><em>AuthorizationException<br> */<br></em>public function create(Request $request)<br>{<br>    $this-&gt;authorize(&#39;create-blog&#39;, $request-&gt;user());<br><br>    return view(&#39;blogs.create&#39;);<br>}<br><br><em>/**<br> * Handles submitting the create a blog form.<br> *<br> * </em><strong><em>@param </em></strong><em>Request $request<br> * </em><strong><em>@param </em></strong><em>Blog $blog<br> * </em><strong><em>@return </em></strong><em>RedirectResponse<br> * </em><strong><em>@throws </em></strong><em>AuthorizationException<br> */<br></em>public function store(Request $request, Blog $blog)<br>{<br>    $this-&gt;authorize(&#39;create-blog&#39;, $request-&gt;user());<br><br>    $request-&gt;validate([<br>        &#39;name&#39; =&gt; [&#39;required&#39;],<br>        &#39;content&#39; =&gt; [&#39;required&#39;]<br>    ]);<br><br>    Blog::<em>create</em>($request-&gt;only(&#39;name&#39;, &#39;content&#39;));<br><br>    return redirect()-&gt;back()<br>        -&gt;with(&#39;success&#39;, &#39;Blog has been created&#39;);<br>}</pre><p>The issues with this is that you’re dealing with a lot in your controller, it may not look so bad in this example but imagine if we had more fields. It is handling; authorisation, validation, business logic &amp; the response. It works well but has caused duplication of code. Now what if we were to structure this like so:</p><p><strong>CreateBlogRequest.php</strong></p><pre>&lt;?php<br><br>namespace App\Http\Requests;<br><br>use Illuminate\Foundation\Http\FormRequest;<br><br>class CreateBlogRequest extends FormRequest<br>{<br>    <em>/**<br>     * Determine if the user is authorized to make this request.<br>     *<br>     * </em><strong><em>@return </em></strong><em>bool<br>     */<br>    </em>public function authorize()<br>    {<br>        return $this-&gt;user()-&gt;can(&#39;create-blog&#39;);<br>    }<br><br>    <em>/**<br>     * Get the validation rules that apply to the request.<br>     *<br>     * </em><strong><em>@return </em></strong><em>array<br>     */<br>    </em>public function rules()<br>    {<br>        if($this-&gt;isMethod(&#39;GET&#39;)) {<br>            return [];<br>        }<br><br>        return [<br>            &#39;name&#39; =&gt; [&#39;required&#39;],<br>            &#39;content&#39; =&gt; [&#39;required&#39;]<br>        ];<br>    }<br>}</pre><p><strong>BlogController.php</strong></p><pre><em>/**<br> * Shows the form for creating a new blog.<br> *<br> * </em><strong><em>@param </em></strong><em>CreateBlogRequest $request<br> * </em><strong><em>@return </em></strong><em>Application|Factory|View<br> */<br></em>public function create(CreateBlogRequest $request)<br>{<br>    return view(&#39;blogs.create&#39;);<br>}<br><br><em>/**<br> * Handles submitting the create a blog form.<br> *<br> * </em><strong><em>@param </em></strong><em>CreateBlogRequest $request<br> * </em><strong><em>@param </em></strong><em>Blog $blog<br> * </em><strong><em>@return </em></strong><em>RedirectResponse<br> */<br></em>public function store(CreateBlogRequest $request, Blog $blog)<br>{<br>    Blog::<em>create</em>($request-&gt;only(&#39;name&#39;, &#39;content&#39;));<br><br>    return redirect()-&gt;back()<br>        -&gt;with(&#39;success&#39;, &#39;Blog has been created&#39;);<br>}</pre><p>As you can see, now our controller is dealing with the logic and returning a response. It’s cleaner to look at and is better for maintaining and being more efficient. Also, we have the logic for authorizing this request for both showing and submitting the form in a single place.</p><h3>Modules folder</h3><p>Where do your place all your model classes? Straight into the <em>app</em> directory? Maybe even into a <em>models</em> directory inside <em>app</em>? Whichever you use, there’s nothing wrong with either way, but what if you have 10+ of these classes to handle. Having them all in one place can easily make this seem cluttered (in my opinion).</p><p>I like to think of keeping the <em>app </em>directory<em> </em>only for handling HTTP requests, this means I need somewhere to host everything else. This is where the <em>modules</em> folder comes in.</p><p>Modules are split into defining categories, for example the following modules could be for a booking system:</p><ul><li>Auth (Users, Teams, Roles)</li><li>Customers (Customers, Contacts, Addresses)</li><li>Bookings (Bookings)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*yzt8WUG83B6U3ATbHB3zvw.png" /><figcaption>Modules folder example</figcaption></figure><p>As you can see here, this can be opened up to include more than just models, each module can have its purpose defined provider, notifications can be categorised as well as Jobs. You can even go as far as to including migrations and seeder classes.</p><p>I access each of these classes by defining my own project specific namespace, such as <em>JoshsCRM\Auth\Models\User</em>. You can do this by added the following line in <em>composer.json</em>.</p><pre>},<br>&quot;autoload&quot;: {<br>    &quot;psr-4&quot;: {<br>        &quot;App\\&quot;: &quot;app/&quot;,<br>        &quot;JoshsCRM\\&quot;: &quot;modules/&quot;,<br>        &quot;Database\\Factories\\&quot;: &quot;database/factories/&quot;,<br>        &quot;Database\\Seeders\\&quot;: &quot;database/seeders/&quot;<br>    }<br>},</pre><p>You’ll need to run composer dump-autoload for this to take effect.</p><h3>Services</h3><p>Earlier in my blog example when dealing with requests we dealt with creating the blog directly in the controller. This works fine, but what if we only wanted to create a blog for a given Team. We’d be doing this.</p><p><strong>BlogController.php</strong></p><pre><em>/**<br> * Handles submitting the create a blog form.<br> *<br> * </em><strong><em>@param </em></strong><em>CreateBlogRequest $request<br> * </em><strong><em>@param </em></strong><em>Blog $blog<br> * </em><strong><em>@return </em></strong><em>RedirectResponse<br> */<br></em>public function store(CreateBlogRequest $request, Blog $blog)<br>{<br>    //Get the current team for this request<br>    $team = $request-&gt;team();<br><br>    Blog::<em>create</em>([<br>        &#39;name&#39; =&gt; $request-&gt;input(&#39;name&#39;),<br>        &#39;content&#39; =&gt; $request-&gt;input(&#39;content&#39;),<br>        &#39;team_id&#39; =&gt; $team-&gt;getKey()<br>    ]);<br><br>    return redirect()-&gt;back()<br>        -&gt;with(&#39;success&#39;, &#39;Blog has been created&#39;);<br>}</pre><p>The issue here is that we are relying on our controller to be handling logic which could be used elsewhere in the application. Say you were to allow a blog to be associated with multiple teams in the future, you’d have to go through everywhere you’ve implemented this and make a change.</p><p>Now what if we were to put this into a service class.</p><p><strong>BlogService.php</strong></p><pre>&lt;?php<br><br>namespace App\Services;<br><br>use App\Blog;<br>use App\Team;<br>use Illuminate\Database\Eloquent\Builder;<br>use Illuminate\Database\Eloquent\Model;<br><br>class BlogService<br>{<br><br>    <em>/**<br>     * Creates a new Blog in storage for the given $team.<br>     * <br>     * </em><strong><em>@param </em></strong><em>array $data<br>     * </em><strong><em>@param </em></strong><em>Team $team<br>     * </em><strong><em>@return </em></strong><em>Builder|Model<br>     */<br>    </em>public static function createForTeam(array $data, Team $team)<br>    {<br>        $data[&#39;team_id&#39;] = $team-&gt;getKey();<br><br>        return Blog::<em>query</em>()-&gt;create($data);<br>    }<br>}</pre><p><strong>BlogController.php</strong></p><pre><em>/**<br> * Handles submitting the create a blog form.<br> *<br> * </em><strong><em>@param </em></strong><em>CreateBlogRequest $request<br> * </em><strong><em>@param </em></strong><em>Blog $blog<br> * </em><strong><em>@return </em></strong><em>RedirectResponse<br> */<br></em>public function store(CreateBlogRequest $request, Blog $blog)<br>{<br>    //Get the current team for this request<br>    $team = $request-&gt;team();<br><br>    BlogService::<em>createForTeam</em>($request-&gt;only(&#39;name&#39;, &#39;content&#39;), $team);<br><br>    return redirect()-&gt;back()<br>        -&gt;with(&#39;success&#39;, &#39;Blog has been created&#39;);<br>}</pre><p>As you can see, we’ve stripped back our controller even further to not be handling any business logic. This is now solely dealing with handling a request and returning a response, we have all business logic in our service. My general rule of thumb is to leave interacting with a model outside of the controller and in a service.</p><p>What’s more? You could place this in the appropriate module folder such as <em>modules/Blogs/Services/BlogService.php.</em></p><h3>Route separation</h3><p>I see the routes as a similar issue to how I see models in a single folder. All defined in a single <em>web.php, </em>containing hundreds of lines of defined routes. What can you do to make this file easy to read?</p><ul><li>Add a comment to each route?</li><li>Group particular areas of a system together?</li></ul><p>Each of these are great points and easily achievable, both of which I still do. However it still doesn’t get around the file being hundreds of lines long, maybe even thousands depending on the size of the build.</p><p>How about grouping each area of the project into its own route file, similar structure to how we categorised the models earlier. Say we have a directory inside routes called <em>web </em>where we can add and remove route groups as we please? It would look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*9zM7XQirpRZxpBfvqNS1DQ.png" /><figcaption>Routes separation example</figcaption></figure><p>Here we don’t need to scroll down a single route file to find the blog routes or the profile routes. You don’t need to make it a pain to add further route files either, just use this block of code in your web.php to auto-detect these.</p><pre>&lt;?php<br><br>use App\Http\Controllers\WelcomeController;<br>use Illuminate\Support\Facades\Route;<br><br>Route::get(&#39;/&#39;, [WelcomeController::class, &#39;handle&#39;]);<br><br>$files = glob(base_path(&#39;routes/web/*.php&#39;), <em>GLOB_BRACE</em>);<br>foreach ($files as $file)<br>    require $file;</pre><p>So, what do you think? Do you agree with any of the solutions above to making your code that little bit easier to navigate &amp; understand? Share your opinions and let me know if you have any good practices you tend to stick to.</p><p>I don’t take ownership in any of the methods used above, most I have picked up from other developers through my time and just wanted to share them onwards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5a4366169c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>