<?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"><channel><title><![CDATA[Hayatu Abubakar]]></title><description><![CDATA[Hayatu Abubakar]]></description><link>https://hayatu.xyz</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 09:22:39 GMT</lastBuildDate><atom:link href="https://hayatu.xyz/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing Custom Exceptions in Laravel 9]]></title><description><![CDATA[How to handle exceptions and show custom errors in Laravel 9]]></description><link>https://hayatu.xyz/writing-custom-exceptions-in-laravel-9</link><guid isPermaLink="true">https://hayatu.xyz/writing-custom-exceptions-in-laravel-9</guid><category><![CDATA[Laravel 9]]></category><category><![CDATA[exceptionhandling]]></category><category><![CDATA[laravel-exception]]></category><dc:creator><![CDATA[Hayatu Abubakar]]></dc:creator><pubDate>Sat, 28 Jan 2023 12:34:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674906698872/33e4b751-e701-4aa4-ba94-d6c02b55c3f0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In every codebase, there is always one error that it throws, and will definitely not make sense for it to be shown to the user. An example is the Page not Found or 404 error. In cases like that, it is better to show the user a page explaining that the page they are trying to access does not exist. Another type is a case where you are calling an API and displaying a page depending on the HTTP response from that API. When it comes back with a response that is an error, your code may just throw an error, and the user has no idea what it means. In this article, I will build a Laravel app that makes a request to the <a target="_blank" href="https://www.omdbapi.com/">OMDB API</a> and handle the exceptions when an error response is received using custom exceptions.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li><p>Prior Knowledge of Laravel and PHP</p>
</li>
<li><p>Code Editor</p>
</li>
<li><p>PHP 8.0+ installed</p>
</li>
<li><p>Laravel 9</p>
</li>
<li><p>MySQL 8.30 installed</p>
</li>
<li><p>Composer installed</p>
</li>
<li><p>Node &amp; NPM installed</p>
</li>
</ul>
<h2 id="heading-setup">Setup</h2>
<p>To set up your environment, follow the guide on the Laravel page via this <a target="_blank" href="https://laravel.com/docs/9.x/installation">link</a>. To create a new Laravel project, type the following commands in your CLI:</p>
<pre><code class="lang-bash">composer create-project laravel/laravel custom-exception
</code></pre>
<p>This will create a new project in the folder. We can start the project by running the following commands:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> custom-exception &amp;&amp; php artisan serve
</code></pre>
<p>The command will run the Laravel development server, and you should see the Laravel welcome page.</p>
<p><img src="https://lh3.googleusercontent.com/rBBGSdUKe7trGkRvHoFNhkfQWiv13JnLf9Q0_boOBi4JgpjTAYff7ft-eq9Q_5gz_roTK9dlBzF7_ILuOf1vbwuCVtR_qY3x5IKy8lcG__cj8HnLocEjWsl3CLyjyT5C4T7jUZKlzlzAo_77AE9RnLJu9qka8xhTfZU3xBDoelgUPGQhvwkH9h1rV5lF7w" alt="Image by Author" class="image--center mx-auto" /></p>
<p><em>Image by Author</em></p>
<p>We will go ahead and create a resource controller named MoviesController by typing the command below:</p>
<pre><code class="lang-bash">php artisan make:controller MoviesController --resource
</code></pre>
<p>We will create just two routes for all we are going to do. They are shown below:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
Route::get( <span class="hljs-string">'/'</span>,[MoviesController::class, <span class="hljs-string">'index'</span>]);
Route::get(<span class="hljs-string">'/results'</span>,[ MoviesController::class, <span class="hljs-string">'search_movie'</span>]);
</code></pre>
<p>The API we will be using is the <a target="_blank" href="https://www.omdbapi.com/">OMDB API</a>, which is an abstraction of the IMD API. We will write code that calls the API and return a JSON response. For that, we will make a service class called IMDBService. It will be the class that performs the HTTP calls to the API and formats results in JSON to be displayed. The code is below:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Client</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Http</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Support</span>\<span class="hljs-title">Facades</span>\<span class="hljs-title">Log</span>;
<span class="hljs-class"><span class="hljs-keyword">Class</span> <span class="hljs-title">IMDBService</span> </span>{
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">search_title</span>(<span class="hljs-params">$title</span>)
    </span>{
        $url = config(<span class="hljs-string">'settings.imdb_url'</span>).<span class="hljs-string">'/?t='</span>.$title.<span class="hljs-string">'&amp;apikey='</span>.config(<span class="hljs-string">'settings.imdb_key'</span>);
        $response = Http::get($url);
        <span class="hljs-keyword">return</span> $response-&gt;json();
    }
}
</code></pre>
<h2 id="heading-creating-custom-exception">Creating Custom Exception</h2>
<p>Because of the way responses are sent by an API, there may be instances where an error response is thrown. We can let the system throw an error, but that will not look good to the user. It is better to show the user what they will understand. For that, we will create a custom exception like below:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Exceptions</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Exception</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MoviesException</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Exception</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">report</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params">$request</span>)
    </span>{
        <span class="hljs-keyword">return</span> response()-&gt;view(<span class="hljs-string">'errors.invalid-input'</span>, [<span class="hljs-string">'message'</span>=&gt; <span class="hljs-keyword">$this</span>-&gt;message], <span class="hljs-number">500</span>);
    }
}
</code></pre>
<p>This exception class does two things when called, render and report the exception. The render method receives the request object and returns a custom error view that we defined as <code>invalid-input</code>. The report function can be used to send messages about the error through email, slack, or any other service you use. With this class, we can control how we handle the exception and what we show the user. We will then go ahead and create another service class called MoviesService that will call this IMDB class to make requests to the API and handle responses accordingly. In this class, we will return a response to the user when a movie is found and then throw errors when an error is returned. The JSON response comes with a key-value pair we can always check to know if a request is successful. Here is the class:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">IMDBService</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Exceptions</span>\<span class="hljs-title">MoviesException</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MoviesService</span> 
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get_movie</span>(<span class="hljs-params">$title</span>)
    </span>{
        $movie = json_decode(json_encode(IMDBService::search_title($title)));
        <span class="hljs-keyword">if</span> ($movie-&gt;Response == <span class="hljs-string">"True"</span>) {
            <span class="hljs-keyword">return</span> $movie;
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> MoviesException($movie-&gt;Error, <span class="hljs-number">1</span>);

    }
}
</code></pre>
<p>In the code above, you will notice we are throwing the MoviesException we created. Instead of just passing the response from the server straight to the user, we are sending the error message to the exception class. This will make sure a human-friendly message is shown to the user. The next code to write is the one to show the users the form to search for the movie given the title. We will add the function below to our MoviesController class:</p>
<pre><code class="lang-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">search_movie</span>(<span class="hljs-params">Request $request</span>)
    </span>{
        $result = MoviesService::get_movie($request-&gt;input(<span class="hljs-string">'title'</span>));
        <span class="hljs-keyword">return</span> $result;
    }
</code></pre>
<p>The Full MoviesController Class will look like this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Controllers</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">Illuminate</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Request</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">App</span>\<span class="hljs-title">Services</span>\<span class="hljs-title">MoviesService</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MoviesController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-comment">/**
    Display the search form.
    <span class="hljs-doctag">@return</span> \Illuminate\Http\Response
    **/</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">index</span>(<span class="hljs-params"></span>)
    </span>{
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'search'</span>);
    }
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">search_movie</span>(<span class="hljs-params">Request $request</span>)
    </span>{
        $result = MoviesService::get_movie($request-&gt;input(<span class="hljs-string">'title'</span>));
        <span class="hljs-keyword">return</span> view(<span class="hljs-string">'result'</span>, [<span class="hljs-string">'result'</span> =&gt; $result]);
    }
}
</code></pre>
<p>The view to display the search page is shown below:</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- Search Page --&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Search a Movie<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    @vite('resources/css/app.css')
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"my-60 mx-auto max-w-7xl px-4 sm:px-6 lg:px-8"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- We've used 3xl here, but feel free to try other max-widths based on your needs --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-2xl"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-5 mx-auto font-bold text-5xl text-center"</span>&gt;</span>IMDB Search<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/results"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"get"</span>&gt;</span>
                @csrf
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"title"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"title"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter The Movie Title"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"inline-flex w-full rounded-md border-gray-300 pr-12 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"</span> <span class="hljs-attr">required</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">" mx-2 inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-6 py-3 text-base font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Search<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>And the one for the results page is here:</p>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- Results Page --&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    @vite('resources/css/app.css')
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Search Result<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-7xl px-4 sm:px-6 lg:px-8"</span>&gt;</span>
            <span class="hljs-comment">&lt;!-- We've used 3xl here, but feel free to try other max-widths based on your needs --&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-3xl"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-8 overflow-hidden bg-white shadow sm:rounded-lg"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"px-4 py-5 sm:px-6"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-lg font-medium leading-6 text-gray-900"</span>&gt;</span>{{$result-&gt;Title}}<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 max-w-2xl text-sm text-gray-500"</span>&gt;</span>IMDB Rating: {{$result-&gt;imdbRating}}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"border-t border-gray-200 px-4 py-5 sm:p-0"</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">dl</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sm:divide-y sm:divide-gray-200"</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5 sm:px-6"</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dt</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-medium text-gray-500"</span>&gt;</span>Director<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dd</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"</span>&gt;</span>{{$result-&gt;Director}}<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5 sm:px-6"</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dt</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-medium text-gray-500"</span>&gt;</span>Released<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dd</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"</span>&gt;</span>{{$result-&gt;Released}}<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5 sm:px-6"</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dt</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-medium text-gray-500"</span>&gt;</span>Genre<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dd</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"</span>&gt;</span>{{$result-&gt;Genre}}<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5 sm:px-6"</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dt</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-medium text-gray-500"</span>&gt;</span>Actors<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dd</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"</span>&gt;</span>{{$result-&gt;Actors}}<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"py-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:py-5 sm:px-6"</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dt</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-sm font-medium text-gray-500"</span>&gt;</span>Plot<span class="hljs-tag">&lt;/<span class="hljs-name">dt</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">dd</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-1 text-sm text-gray-900 sm:col-span-2 sm:mt-0"</span>&gt;</span>{{$result-&gt;Plot}}<span class="hljs-tag">&lt;/<span class="hljs-name">dd</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">dl</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>For the errors, we will make a view that will render an error depending on what the error message is. The view is shown below:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"my-48 mx-auto max-w-7xl px-4 sm:px-6 lg:px-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto max-w-3xl text-center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">svg</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">"http://www.w3.org/2000/svg"</span> <span class="hljs-attr">fill</span>=<span class="hljs-string">"none"</span> <span class="hljs-attr">viewBox</span>=<span class="hljs-string">"0 0 24 24"</span> <span class="hljs-attr">stroke-width</span>=<span class="hljs-string">"1.5"</span> <span class="hljs-attr">stroke</span>=<span class="hljs-string">"currentColor"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mx-auto my-5 w-14 h-14 stroke-red-500"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">path</span> <span class="hljs-attr">stroke-linecap</span>=<span class="hljs-string">"round"</span> <span class="hljs-attr">stroke-linejoin</span>=<span class="hljs-string">"round"</span> <span class="hljs-attr">d</span>=<span class="hljs-string">"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">svg</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"font-bold text-3xl font-mono text-red-500"</span>&gt;</span>API Error<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"font-semibold my-4"</span>&gt;</span>{{$message}}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The <code>$message</code> variable is the string error message from the API. There are instances where this error message may not make sense to the user, and for that, we can implement a controller that shows different messages that the user can understand instead of what is returned from the API as a response to our request.</p>
<h2 id="heading-running-the-code">Running the Code</h2>
<p>Putting everything together to run the code, we will see the search page like this</p>
<p><img src="https://lh4.googleusercontent.com/i3mLP79BS2xZZHOC6pqEKvGrXeZES9-mWUcVePDzarjaOd2AOLC6sI7nXqkazgoAijQ3tDo6DboZJ3Ln2myxl5jmI6LeL_SqSlIlYP8IaS2IBDq-1CHyTJdAw8qisC4vTXCI8OEC9a0R9JifLyNMgKlz2euRo6ZXYCEvCaU4Y0DB0K3XlxnFNzBzfO19qQ" alt class="image--center mx-auto" /></p>
<p><em>Image by Author</em></p>
<p>When you type to search for a movie that exists, this is the response you will get</p>
<p><img src="https://lh3.googleusercontent.com/lPol4-LM6pDflmYM9ekbqmd3ZBV8adMyVp-YZ_V5gT9dd762S9mzQZaEkaPkpNlCjRKAYnkg2eCPklQsWrTZrrOi31Oe0mdXqC7JG390K0ZynnWa5lrIrrdj1OhTBSgqsNMFD_qvNSENN0d3hD-eKeDhgTkETJhnHEQ92NNAHNAx4kqvPtxlVs23vFeC8g" alt class="image--center mx-auto" /></p>
<p><em>Image by Author</em></p>
<p>And if it fails, this is the page you will get</p>
<p><img src="https://lh3.googleusercontent.com/c2HaKBg1IZ5aIT9rHVUz0hheMcRVHokIHewN_3Um71sR6nJvZg-dA2NjHiFd5DGNqZIcndL8X71kzsq31mYkzcDUVK-A13Ie2blcSLqlHXz0aN7WpelDgNLyfilg50fSF5FXQfxPr3g0m2VtelUmZebn4u2EpCvtEnfQA9LDK8Z-hO8si6KJAeS3Kj0FDg" alt class="image--center mx-auto" /></p>
<p><em>Image by Author</em></p>
<p>The error message “Movie Not Found!” is the error message from the API response. We left it there because this is very clear to the user. If it were a cryptic message that the user might not understand, we may handle it by making a class to show us a view and message depending on the error code and message we receive from the API.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Handling errors in any application is crucial. Laravel has made it easy to handle almost everything that will be thrown at you, even if you may not know what it is. In this article, we have seen how it's possible to tailor your error messages to the type of responses you receive from an API. I hope I have been available to share something amazing to help you achieve your goal. The link to the repo on GitHub is <a target="_blank" href="https://github.com/hayatu89/custom-exception">here</a>. You can use it as a base for any custom exception you want to handle in your Laravel 9 Project. Happy Coding!</p>
<h2 id="heading-credits">Credits</h2>
<ul>
<li><p><a target="_blank" href="https://laravel.com/docs/9.x/errors">Laravel Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.omdbapi.com/">OMDP API</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Introduction to Phoenix LiveView]]></title><description><![CDATA[Coding Rich Interactive User Interfaces in Elixir]]></description><link>https://hayatu.xyz/introduction-to-phoenix-liveview</link><guid isPermaLink="true">https://hayatu.xyz/introduction-to-phoenix-liveview</guid><category><![CDATA[Phoenix framework]]></category><category><![CDATA[phoenix liveview]]></category><category><![CDATA[genserver]]></category><dc:creator><![CDATA[Hayatu Abubakar]]></dc:creator><pubDate>Mon, 21 Nov 2022 08:56:13 GMT</pubDate><content:encoded><![CDATA[<p>Maintaining codebases with JavaScript can be a hassle. From trying to keep your bundle size small to ensure you have the correct linting. Some developers (like me) like to write in one language for both the front and back end. </p>
<p>Enter LiveView</p>
<p>As defined in the <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html">docs</a>, "LiveView provides rich, real-time user experiences with server-rendered HTML." LiveView is the Frontend Engine that comes coupled with the Elixir Framework Phoenix. It performs all the magic you can do with JavaScript on the Frontend. It is written in Elixir and runs on the Erlang BEAM (The Erlang Virtual Machine). It is implemented as a Genserver process.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>In this tutorial, we will build a simple web page that changes the name provided with another one using the Phoenix Framework, and I will be walking you through how to set it up and use it.</p>
<ul>
<li><p>Basic knowledge of Genservers</p>
</li>
<li><p>Basic knowledge of Phoenix Framework</p>
</li>
<li><p>Code Editor (VS Code preferably)</p>
</li>
<li><p>Basic HTML &amp; CSS knowledge</p>
</li>
</ul>
<h2 id="heading-installation">Installation</h2>
<p>To get LiveView, you need to install <a target="_blank" href="https://elixir-lang.org/install.html">Elixir and its dependencies</a>, and then install <a target="_blank" href="https://hexdocs.pm/phoenix/installation.html">Phoenix Framework</a>. LiveView comes as a part of Phoenix v1.5 and upwards. We will be using LiveView with a new installation. If you want to add it to your existing Phoenix project, follow the guide on the docs <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/installation.html#existing-projects">page</a></p>
<p>Once you're done setting up, type the following command in your command line to create a new Phoenix project with LiveView</p>
<pre><code>mix phx.new hash_node --live
</code></pre><p>The <code>--live</code> is the flag that indicates you want to use LiveView in your project.</p>
<p>Once you are done with the setup, open the folder with your favorite code editing tool for the rest of the session. </p>
<h2 id="heading-behavior">Behavior</h2>
<p>LiveView uses a declarative model of programming. This means it does not reload your entire page whenever there is a change to any element. Instead, it keeps a web socket between the client and the server and exchanges messages. If there is any change, a message is sent between the two, and the element that has changed will be the only one that is re-rendered by the server and sent to the client.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667991807786/8CdUIkmZ9.png" alt="LiveView Behavior" /></p>
<h2 id="heading-life-cycle">Life Cycle</h2>
<p>LiveView starts as a typical HTML rendered through normal HTTP requests, as stated in the image above. But it is then upgraded to a stateful view when a connection is established between the client and the server. Even when JavaScript is disabled, the connection persists, and changes will be rendered.
When LiveView is rendered for the first time, the <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:mount/3"><code>mount/3</code></a> callback is invoked. This callback will carry any parameters the server wants to send to the client, the session data, and the socket. Here is what it will look like:</p>
<pre><code>def mount(_params, _session, socket) <span class="hljs-keyword">do</span>
  {:ok, socket |&gt; assign(socket)}
end
</code></pre><p>After this, the <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:handle_params/3"><code>handle_params/3</code></a>is called if there are any URI or form parameters that are to be handled, and finally, the  <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:render/1"><code>render/1</code></a> is called to render the actual page to the user.</p>
<pre><code> def render(assigns) <span class="hljs-keyword">do</span>
        ~H<span class="hljs-string">""</span><span class="hljs-string">"
            &lt;h1&gt; Hello!&lt;/h1&gt;
            &lt;p&gt; This is an example of LiveView
        "</span><span class="hljs-string">""</span>
    end
</code></pre><p>When the page is rendered, a connection between the server and client is kept alive using web sockets. When there is a change on the page, it will be handled by the <code>handle_params/3</code> callback, and <code>render/1</code> is called again to view the change. For the server to interact with client events, <code>phx-</code> bindings are used in the frontend code and the <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#c:handle_event/3"><code>handle_event/3</code></a> handles that. A full list of all the bindings is <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/bindings.html">here</a></p>
<h2 id="heading-how-to-use-liveview">How To Use LiveView</h2>
<p>Using LiveView in your Phoenix project can either be by using it on your .heex template files directly or as components. We will be implementing the direct option, but you can check out the components via this <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveComponent.html">link</a> on the LiveView Component documentation.</p>
<p>After setting up, the next thing to do is to prepare the route where LiveView will be used. Find your <code>router.ex</code> file in your project and add the LiveView route underneath the scope you want to use it</p>
<pre><code>defmodule HashNodeWeb.Router <span class="hljs-keyword">do</span>
  use HashNodeWeb, :router
  scope <span class="hljs-string">"/"</span>, HashNodeWeb <span class="hljs-keyword">do</span>
    <span class="hljs-attr">pipe_through</span> :browser

    get <span class="hljs-string">"/"</span>, PageController, :index
    live <span class="hljs-string">"/hashnode"</span>, HashLive
  end
end
</code></pre><p>After that, create the module that will contain the LiveView code, in this case, it will be <code>hash_live.ex</code> and is located in the path <code>/lib/hash_node_web/controllers/live/</code>.  </p>
<pre><code>defmodule HashNodeWeb.Live.HashLive <span class="hljs-keyword">do</span>
  use Phoenix.LiveView
  def render(assigns) <span class="hljs-keyword">do</span>
    ~H<span class="hljs-string">""</span><span class="hljs-string">"
    &lt;h1&gt;Hash Node&lt;/h1&gt;
    "</span><span class="hljs-string">""</span>
  end
  def mount(_params, _session, socket) <span class="hljs-keyword">do</span>
    {:ok, socket}
  end
end
</code></pre><p>Save the file and run <code>`mix phx.server</code> on the cli. YYou may run into some errors with the database connection, but your application will work. You can disable Repo if you don't want to see the errors. At this phase, this is what you will see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668069406747/sE_ajR3Sh.png" alt="LiveView v1.png" /></p>
<p>As you can see, the H1 tag we wrote in the <code>render/1</code> definition is what was rendered on the page. Let's go ahead and add some reactivity on the page to see how that works. We will add a button and a name that changes to another name when you click the button. For that, we will introduce some bindings in <code>render/1</code>, a parameter in <code>mount/3</code>, and the <code>handle_event/3</code> definition in our code. The complete code will now look like this</p>
<pre><code>defmodule HashNodeWeb.Live.HashLive <span class="hljs-keyword">do</span>
  use Phoenix.LiveView
  def render(assigns) <span class="hljs-keyword">do</span>
    ~H<span class="hljs-string">""</span><span class="hljs-string">"
    &lt;h1&gt;Hash Node&lt;/h1&gt;
    &lt;p&gt; &lt;%= @name %&gt; &lt;/p&gt;
    &lt;button class="</span>btn btn-lg<span class="hljs-string">" phx-click="</span>click<span class="hljs-string">" phx-value-randomize="</span><span class="hljs-literal">true</span><span class="hljs-string">"&gt; Change Name &lt;/button&gt;
    "</span><span class="hljs-string">""</span>
  end
  def handle_event(<span class="hljs-string">"click"</span>,  %{<span class="hljs-string">"randomize"</span> =&gt; randomize}, socket) <span class="hljs-keyword">do</span>
    {:noreply, socket |&gt; assign(name: <span class="hljs-string">"Salim"</span>)}
  end
  def mount(_params, _session, socket) <span class="hljs-keyword">do</span>
    {:ok, socket |&gt; assign(name: <span class="hljs-string">"Hayatu"</span>)}
  end

end
</code></pre><p>If everything works fine, you should see this</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.loom.com/share/a97ca677d4814010892ab6741c0135f6">https://www.loom.com/share/a97ca677d4814010892ab6741c0135f6</a></div>
<p>Hooray! We have been able to implement LiveView and manipulate data using bindings! With this, we can go ahead and make our next little project or the new startup you are thinking of (wink wink). With this setup, you can go ahead and do everything on that file. But what if your project grows in complexity and functionality and you want to separate views into individual files? That is where <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-colocating-templates"><strong>Colocating Templates</strong></a> come into consideration. You can basically put all your LiveView codes in the path <code>/lib/hash_node_web/controllers/live/</code>. All you need to do is to remove the <code>render/1</code> definition from <code>hash_live.ex</code> and create a new file in the same path, like <code>hash_live.html.heex</code>. It will look like this</p>
<pre><code>&lt;h1&gt;Hash Node&lt;/h1&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">%=</span> @<span class="hljs-attr">name</span> %&gt;</span> <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-lg"</span> <span class="hljs-attr">phx-click</span>=<span class="hljs-string">"click"</span> <span class="hljs-attr">phx-value-randomize</span>=<span class="hljs-string">"true"</span>&gt;</span> Change Name <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre><h2 id="heading-conclusion">Conclusion</h2>
<p>LiveView is rich with amazing ways to interact with DOM elements using just Elixir. It is quite clear that with LiveView, all you will be doing to make rich interactive user interfaces is just Elixir and some HTML/CSS. We have covered how to set it up from barebones, and then use it in two different ways. This article is just an introduction, as there are some things we could not cover (like components, file uploads, etc.)  because of how broad they are. You can find out so much more about LiveView from the docs <a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html">page</a>. </p>
<p>I hope I have been able to show you how Elixir can help you achieve almost everything without the need for outside plugins or languages. Happy Coding!</p>
<h2 id="heading-credits">Credits</h2>
<ul>
<li><p><a target="_blank" href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html">Phoenix LiveView Docs</a></p>
</li>
<li><p><a target="_blank" href="https://gist.github.com/shubie/8fedbf4ec478e8bdfe6ccad9e160e6fb">Shuaib Afegbua’s gist</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>