<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Abhishek G</title>
	<atom:link href="https://abhishekg.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>https://abhishekg.com/blog/</link>
	<description>Coder</description>
	<lastBuildDate>Sun, 05 Sep 2021 17:50:14 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.1</generator>
<site xmlns="com-wordpress:feed-additions:1">35871122</site>	<item>
		<title>PHP syntactic sugar code example</title>
		<link>https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/</link>
					<comments>https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/#respond</comments>
		
		<dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
		<pubDate>Sun, 05 Sep 2021 17:50:07 +0000</pubDate>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[syntactic sugar]]></category>
		<guid isPermaLink="false">http://abhishekg.com/blog/?p=699</guid>

					<description><![CDATA[<p>According to Wikipedia, Syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. Though PHP doesn&#8217;t necessarily have much concept of sugaring, I across this one example sometime back. The idea here is to add a given set of values to an array but at &#8230; </p>
<p class="link-more"><a href="https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/" class="more-link">Continue reading<span class="screen-reader-text"> "PHP syntactic sugar code example"</span></a></p>
<p>The post <a href="https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/">PHP syntactic sugar code example</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>According to Wikipedia, <strong>Syntactic sugar</strong> is <a href="https://en.wikipedia.org/wiki/Syntax_(programming_languages)">syntax</a> within a <a href="https://en.wikipedia.org/wiki/Programming_language">programming language</a> that is designed to make things easier to read or to express.</p>



<p>Though PHP doesn&#8217;t necessarily have much concept of sugaring, I across this one example sometime back. The idea here is to add a given set of values to an array but at the alternating ends.</p>



<h3 class="wp-block-heading">Example</h3>



<p><meta charset="utf-8">For a given set of values, 10, 12, 124, 349, 43, 0, 493, 3, 32. The output should have values pushed to each end alternatively. So, the first value into the array would be 10, 2nd would be 12, pushed to the end (or at the start), 3rd pushed other and so on.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#1    #2    #3    #4    #5    #6    #7    #8    #9
                                                32
                                    493   493   493
                        43    43    43    43    43
            124   124   124   124   124   124   124
10    10    10    10    10    10    10    10    10
      12    12    12    12    12    12    12    12
                  349   349   349   349   349   349
                              0     0     0     0
                                          3     3</pre>



<p>The function here loops over an array pushes values in array <code>$e</code> alternatively.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$x = [10, 12, 124, 349, 43, 0, 493, 3, 32];
$i = 0;
foreach ($e as $v) {
      (array_.[unshift,push][++$i%2])($e,$d);
}</pre>



<p>It&#8217;s an array with the two function names <code>['array_push','array_unshift']</code> with <code>[++$i%2]</code> as the index of the array alternating between a <code>0</code> or <code>1</code> so will evaluate to the other function each time. PHP&#8217;s &#8220;variable functions&#8221; let you assign a variable to a function and execute by calling with parenthesis (ex: <code>$f='array_push'; $f($e,$d);</code> == <code>array_push($e,$d)</code>) so the <code>($e,$d)</code> is then calling the evaluated element of the array.</p>



<p>Just a shorter way to do</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if (++$i%2)
      array_push($e,$d);
else
      array_unshift($e,$e);</pre>
<p>The post <a href="https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/">PHP syntactic sugar code example</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://abhishekg.com/blog/2021/09/php-syntactic-sugar-code-example/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">699</post-id>	</item>
		<item>
		<title>Python convert random string date format to Datetime</title>
		<link>https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/</link>
					<comments>https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/#respond</comments>
		
		<dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
		<pubDate>Mon, 12 Jul 2021 09:17:04 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://abhishekg.com/blog/?p=793</guid>

					<description><![CDATA[<p>Development in PHP is easy or it may be just that I&#8217;ve been writing code in PHP for long time. And anytime I had a string date that needs to be converted in another format, all that was required was. It&#8217;s that simple. Do not need any package or library, this is built-in functionality. Now &#8230; </p>
<p class="link-more"><a href="https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/" class="more-link">Continue reading<span class="screen-reader-text"> "Python convert random string date format to Datetime"</span></a></p>
<p>The post <a href="https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/">Python convert random string date format to Datetime</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Development in PHP is easy or it may be just that I&#8217;ve been writing code in PHP for long time. And anytime I had a string date that needs to be converted in another format, all that was required was.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));</pre>



<p>It&#8217;s that simple. Do not need any package or library, this is built-in functionality. Now the original date, could be <code data-enlighter-language="php" class="EnlighterJSRAW">Y-m-d</code> or <code><code data-enlighter-language="php" class="EnlighterJSRAW">Y-m-d H:i</code></code> or <code><code data-enlighter-language="php" class="EnlighterJSRAW">Y-m-d H:i:s</code></code>, where <code data-enlighter-language="generic" class="EnlighterJSRAW">H</code> is hour, <code data-enlighter-language="generic" class="EnlighterJSRAW">i</code> is minute and <code data-enlighter-language="generic" class="EnlighterJSRAW">s</code> is seconds, the above example works for all formats.</p>



<p>This week I had a small python script to fix. Firstly, for almost anything in Python you need to import packages and I used <code data-enlighter-language="generic" class="EnlighterJSRAW">datetime</code> package, the issue with this was <code><code data-enlighter-language="python" class="EnlighterJSRAW">datetime.strptime(date, format)</code></code> expects <code data-enlighter-language="generic" class="EnlighterJSRAW">date</code> to be formatted same as <code data-enlighter-language="generic" class="EnlighterJSRAW">format</code> for it to convert into datetime object.</p>



<p>For example, if the date was say <code><code data-enlighter-language="generic" class="EnlighterJSRAW">2021-06-10 11:10</code></code> and the format provided was <code><code data-enlighter-language="generic" class="EnlighterJSRAW">%Y-%m-%d %H:%M:%S</code></code> it just wouldn&#8217;t work. Python expects the format be <code><code data-enlighter-language="generic" class="EnlighterJSRAW">%Y-%m-%d %H:%M</code></code> that is without expecting seconds.</p>



<p>Fix: After a few google searches and trials came across this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import dateutil.parser
yourdate = dateutil.parser.parse(datestring)</pre>



<p>The only library I was able to find was <code><code data-enlighter-language="generic" class="EnlighterJSRAW">dateutil.parser</code></code> which would convert any string date to datetime object be it <code><code data-enlighter-language="generic" class="EnlighterJSRAW">2010-03-21</code></code> or <code><code data-enlighter-language="generic" class="EnlighterJSRAW">2010-03-21 10:12</code></code> or <code><code data-enlighter-language="generic" class="EnlighterJSRAW">2010-03-21 10:12:13</code></code>.</p>
<p>The post <a href="https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/">Python convert random string date format to Datetime</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://abhishekg.com/blog/2021/07/python-convert-random-string-date-format-to-datetime/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">793</post-id>	</item>
		<item>
		<title>Laravel Custom Exception Handlers</title>
		<link>https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/</link>
					<comments>https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/#respond</comments>
		
		<dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
		<pubDate>Thu, 28 Mar 2019 08:32:01 +0000</pubDate>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[function]]></category>
		<category><![CDATA[how to]]></category>
		<category><![CDATA[laravel]]></category>
		<guid isPermaLink="false">http://abhishekg.com/blog/?p=614</guid>

					<description><![CDATA[<p>Laravel throws a large number of exceptions and is very easy to customize them to suit our needs as required. Note: These exceptions are most helpful if you&#8217;re building an API. The code for common exception handler lies in the {project_root}/app/Exceptions/ folder, named Handler.php. The default file looks like this in Laravel 5.7. Some of &#8230; </p>
<p class="link-more"><a href="https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/" class="more-link">Continue reading<span class="screen-reader-text"> "Laravel Custom Exception Handlers"</span></a></p>
<p>The post <a href="https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/">Laravel Custom Exception Handlers</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Laravel throws a large number of exceptions and is very easy to customize them to suit our needs as required.</p>



<p><em>Note: These exceptions are most helpful if you&#8217;re building an API.</em></p>



<p>The code for common exception handler lies in the <code>{project_root}/app/Exceptions/</code> folder, named <code>Handler.php</code>.  The default file looks like this in Laravel 5.7.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}</pre>



<p>Some of the common exceptions that we&#8217;re going to handle in this tutorial are <code><em>AuthenticationException</em></code><em>, </em><code><em>MethodNotAllowedHttpException</em></code><em>, </em><code><em>ModelNotFoundException</em></code><em>, </em><code><em>NotAcceptableHttpException</em></code><em>, </em><code><em>NotFoundHttpException</em></code><em>, </em><code><em>PostTooLargeException</em></code><em>, </em><code><em>ValidationException</em></code>.</p>



<p></p>



<p>Below is the explanation for each variable, functions and handler implemented.</p>



<p><code>protected $dontReport = []</code> is the array of exceptions that Laravel wouldn&#8217;t report. Here we&#8217;re going to mention the exceptions that we don&#8217;t want laravel to report.</p>



<span id="more-614"></span>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * A list of the exception types that should not be reported.
 *
 * @var array
 */
protected $dontReport = [
    AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    ModelNotFoundException::class,
    \Illuminate\Session\TokenMismatchException::class,
    ValidationException::class,
];</pre>



<p>Next is <code>protected $dontFlash</code> which holds the variables for which we don&#8217;t want values to be shown when the exception is being report. Most common of these are <code>password</code> or <code>authorization token</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * A list of the inputs that are never flashed for validation exceptions.
 *
 * @var array
 */
protected $dontFlash = [
    'password',
    'password_confirmation',
];</pre>



<p>Next we define ourselves the structure of json that we&#8217;d like to return in case any of the above exception occurs. For this we create an <code>$errorObj</code> variable and <code>initErrorObj</code> function that defines the structure.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * @var stdClass
 */
private $errorObj;

/**
 * setup basic error Obj with main properties
 *
 * Optional properties that can be added:
 * - details = [];
 * - innererror = [];
 *
 * @return stdClass
 */
private function initErrorObj()
{
    $this->errorObj = new \stdClass();
    $this->errorObj->code = "";
    $this->errorObj->message = "";
    $this->errorObj->target = "";
}</pre>



<p>Next we configure the exception render method which will check if there exists a function for the raised exception and do the needful.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    $this->initErrorObj();

    $reflect = new \ReflectionClass($exception);
    $method = 'handle' . $reflect->getShortName();

    if (method_exists($this, $method)) {
        $this->errorObj->code = $reflect->getShortName();

        return $this->$method($exception)->header('Access-Control-Allow-Origin', '*');
    }

    return parent::render($request, $exception);
}</pre>



<h2 class="wp-block-heading">Authentication Exception</h2>



<p>Whenever an user tries to make an unauthorized request,  an <code>AuthenticationException</code> is raised by Laravel. Over here if the request is made via API call requesting <code>JSON</code> response we return a <code>JSON</code> response otherwise redirect the user to login page.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response 401
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->isJson() || $request->expectsJson()) {
        $this->errorObj = new \stdClass();
        $this->errorObj->code = "AuthenticationException";
        $this->errorObj->message = $exception->getMessage();
        $this->errorObj->message .= " You are not authorised to make this request.";
        $this->errorObj->target = "query";
        
        return response()->json(['error' => $this->errorObj], 401);
    }

    return redirect()->guest('login');
}</pre>



<h2 class="wp-block-heading">Method Not Allowed Http Exception</h2>



<p>This is when the route exists for the request made but the request type does not. Say making a <code>post</code> request when a <code>get</code> request is required would end up throwing <code>MethodNotAllowedHttpException</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * MethodNotAllowedHttpException
 * The used HTTP method is not allowed on this route in the API
 *
 * @param MethodNotAllowedHttpException $exception
 * @return \Illuminate\Http\Response 405
 */
protected function handleMethodNotAllowedHttpException(MethodNotAllowedHttpException $exception)
{
	$this->errorObj->message = "The used HTTP method is not allowed on this route in the API.";
	$this->errorObj->target = "query";
	
	return response()->json(['error' => $this->errorObj], 405);
}</pre>



<h2 class="wp-block-heading">Model Not Found Exception</h2>



<p>This is when a Model is missing. Wonder how this would happen?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * ModelNotFoundException
 * The model is not found with given identifier
 * https://restpatterns.mindtouch.us/HTTP_Status_Codes/422_-_Unprocessable_Entity
 *
 * @param ModelNotFoundException $exception
 * @return \Illuminate\Http\Response 422
 */
protected function handleModelNotFoundException(ModelNotFoundException $exception)
{
	$fullmodel = $exception->getModel();
	$choppedUpModel = explode('\\', $fullmodel);
	$cleanedUpModel = array_pop($choppedUpModel);
	$this->errorObj->message = $cleanedUpModel . " model is not found with given identifier.";
	$this->errorObj->target = $cleanedUpModel;
	
	return response()->json(['error' => $this->errorObj], 422);
}</pre>



<h2 class="wp-block-heading">Not Acceptable Http Exception</h2>



<p>This is when the route and method are both correct but the headers mis-match. Preferably <code>Accept</code> or <code>Content-type</code> headers not appropriately set for an API would throw <code>NotAcceptableHttpException</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * NotAcceptableHttpException
 * The used HTTP Accept header is not allowed on this route in the API
 *
 * @param NotAcceptableHttpException $exception
 * @return \Illuminate\Http\Response 406
 */
protected function handleNotAcceptableHttpException(NotAcceptableHttpException $exception)
{
	$this->errorObj->message = "The used HTTP Accept header is not allowed on this route in the API.";
	$this->errorObj->target = "query";
	
	return response()->json(['error' => $this->errorObj], 406);
}</pre>



<h2 class="wp-block-heading">Not Found Http Exception</h2>



<p>This is when a request is made to a route that does not exist for the API hence throwing <code>NotFoundHttpException</code> with 404 http response code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * NotFoundHttpException
 * The requested path could not match a route in the API
 *
 * @param NotFoundHttpException $exception
 * @return \Illuminate\Http\Response 404
 */
protected function handleNotFoundHttpException(NotFoundHttpException $exception)
{
	$this->errorObj->message = "The requested path could not match a route in the API.";
	$this->errorObj->target = "query";
	
	return response()->json(['error' => $this->errorObj], 404);
}</pre>



<h2 class="wp-block-heading">Post Too Large Exception</h2>



<p>This is when a size of request is too large for the API to handle. Usually occurs with multipart/form-data request sending large files resulting in <code>PostTooLargeException</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * PostTooLargeException
 * The used HTTP method is not allowed on this route in the API
 *
 * @param PostTooLargeException $exception
 * @return \Illuminate\Http\Response 413
 */
protected function handlePostTooLargeException(PostTooLargeException $exception)
{
	$this->errorObj->message = "The payload size too large for the server to handle.";
	$this->errorObj->target = "request";
	
	return response()->json(['error' => $this->errorObj], 413);
}</pre>



<h2 class="wp-block-heading">Validation Exception</h2>



<p>One of the most use functionality of Laravel is it&#8217;s validation module. A single place to format all validation messages is here. Here is an <a rel="noreferrer noopener" aria-label="example (opens in a new tab)" href="http://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/" target="_blank">example</a> showing how to customize error message format with <code>ValidationException</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * ValidationException
 * Parameters did not pass validatio
 * https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md#examples
 *
 * @param ValidationException $exception
 * @return \Illuminate\Http\Response 400
 */
protected function handleValidationException(ValidationException $exception)
{
    $this->errorObj->message = "Parameters did not pass validation";
    $this->errorObj->target = "parameters";
    $this->errorObj->details = [];

    foreach ($exception->validator->errors()->getMessages() as $field => $message) {
        $details = new \stdClass();
        $details->code = "NotValidParameter";
        $details->message = $message[0];
        $details->target = $field;
        if ($field === 'Channel') {
            $details->code = "ParentChildMismatch";
            $details->message = "The requested service did not find a match for the given channel identifier";
        }
        $this->errorObj->details[] = $details;
    }

    return response()->json(['error' => $this->errorObj], 400);
}</pre>



<p>The original code for these Laravel Exception was written by Github user Stad Gent and can be found <a href="https://github.com/StadGent/laravel_site_opening-hours/blob/develop/app/Exceptions/Handler.php">here</a>.</p>
<p>The post <a href="https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/">Laravel Custom Exception Handlers</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://abhishekg.com/blog/2019/03/laravel-exception-handler-for-apis/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">614</post-id>	</item>
		<item>
		<title>Customizing Laravel validation JSON message format</title>
		<link>https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/</link>
					<comments>https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/#comments</comments>
		
		<dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
		<pubDate>Wed, 20 Mar 2019 13:11:38 +0000</pubDate>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[how to]]></category>
		<category><![CDATA[laravel]]></category>
		<guid isPermaLink="false">http://abhishekg.com/blog/?p=626</guid>

					<description><![CDATA[<p>By default laravel gives a good enough JSON format for validation errors but what if you want to customize it? But for this particular project I decided to change the format to this. To achieve this I created a ValidationException handler function in app/Exceptions/Handler.php which helped me catch all the exceptions raised as a result &#8230; </p>
<p class="link-more"><a href="https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/" class="more-link">Continue reading<span class="screen-reader-text"> "Customizing Laravel validation JSON message format"</span></a></p>
<p>The post <a href="https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/">Customizing Laravel validation JSON message format</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>By default laravel gives a good enough JSON format for validation errors but what if you want to customize it?</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#Original JSON format
{
    "message": "The given data was invalid.",
    "errors": {
        "email": [
            "Please enter email address."
        ],
        "password": [
            "Please enter password."
        ]
    }
}</pre>



<p>But for this particular project I decided to change the format to this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="json" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{
    "success": false,
    "success_code": 400,
    "message": "Please enter email address.",
    "errors": [
        {
            "field": "email",
            "message": "Please enter email address."
        },
        {
            "field": "password",
            "message": "Please enter password."
        }
    ]
}</pre>



<p>To achieve this I created a <code>ValidationException</code> handler function in <code>app/Exceptions/Handler.php</code> which helped me catch all the exceptions raised as a result of failed validations.</p>



<span id="more-626"></span>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/**
 * ValidationException
 * Parameters did not pass validation
 *
 * @param ValidationException $exception
 * @return \Illuminate\Http\Response 400
 */
protected function handleValidationException(ValidationException $exception)
{
	$errors = $this->formatErrorBlock($exception->validator);

	$first = '';
	if (!empty($errors) &amp;&amp; !empty($errors[0]))
		$first = $errors[0]['message'];

	$json = new \stdClass;
	$json->success = false;
	$json->success_code = 400;
	$json->message = $first;
	$json->errors = $errors;

	return response()->json($json, 400);
}</pre>



<p>Next I created <code>formatErrorBlock</code> that would loop through all the default error block created by laravel and format them as required.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public function formatErrorBlock($validator)
{
	$errors = $validator->errors()->toArray();
	$return = array();

	foreach ($errors as $field => $message) {
		$r = ['field' => $field];

		foreach ($message as $key => $msg) {
			if ($key) {
				$r['message'.$key] = $msg;
			} else {
				$r['message'] = $msg;
			}
		}

		$return[] = $r;
	}

	return $return;
}</pre>



<p><em>Notice the </em><code><em>if else</em></code><em> block in </em><code><em>foreach</em></code><em> loop. That is because Laravel at times returns multiple errors for a single key hence, I post-fixed the further messages with it&#8217;s respective array key.</em></p>
<p>The post <a href="https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/">Customizing Laravel validation JSON message format</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://abhishekg.com/blog/2019/03/customizing-laravel-validation-json-message-format/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">626</post-id>	</item>
		<item>
		<title>Time killer and addictive Google Games</title>
		<link>https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/</link>
					<comments>https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/#respond</comments>
		
		<dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
		<pubDate>Tue, 19 Mar 2019 11:54:17 +0000</pubDate>
				<category><![CDATA[Google]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[game]]></category>
		<guid isPermaLink="false">http://abhishekg.com/blog/?p=598</guid>

					<description><![CDATA[<p>We&#8217;ve all at least once played the T-rex game on Google Chrome when the internet was done. But do you know Google offers more such games? Of course, these others require a working internet. . 1. 30th Anniversary of PAC-MANGoogle came out with one of the most addictive classic Pac-man game doodle on it&#8217;s 30th &#8230; </p>
<p class="link-more"><a href="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/" class="more-link">Continue reading<span class="screen-reader-text"> "Time killer and addictive Google Games"</span></a></p>
<p>The post <a href="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/">Time killer and addictive Google Games</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>We&#8217;ve all at least once played the T-rex game on Google Chrome when the internet was done. But do you know Google offers more such games? Of course, these others require a working internet. .</p>



<p>1.  <a href="https://www.google.com/doodles/30th-anniversary-of-pac-man">30th Anniversary of PAC-MAN</a><br>Google came out with one of the most addictive classic Pac-man game doodle on it&#8217;s 30th Anniversary on May 21, 2010. Go ahead and give it a try.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="486" height="208" data-attachment-id="600" data-permalink="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/google-pacman-game-doogle/" data-orig-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?fit=486%2C208&amp;ssl=1" data-orig-size="486,208" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="google-pacman-game-doogle" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?fit=300%2C128&amp;ssl=1" data-large-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?fit=486%2C208&amp;ssl=1" src="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?resize=486%2C208" alt="" class="wp-image-600" srcset="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?w=486&amp;ssl=1 486w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-pacman-game-doogle.png?resize=300%2C128&amp;ssl=1 300w" sizes="(max-width: 486px) 100vw, 486px" /></figure></div>



<p>2. <a href="https://www.google.com/doodles/basketball-2012">Basketball 2012</a><br>If you&#8217;re into basket ball, this one is definitely for you.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="525" height="213" data-attachment-id="609" data-permalink="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/basketball-google-2012/" data-orig-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?fit=534%2C217&amp;ssl=1" data-orig-size="534,217" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="basketball-google-2012" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?fit=300%2C122&amp;ssl=1" data-large-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?fit=525%2C213&amp;ssl=1" src="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?resize=525%2C213" alt="" class="wp-image-609" srcset="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?w=534&amp;ssl=1 534w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/basketball-google-2012.png?resize=300%2C122&amp;ssl=1 300w" sizes="(max-width: 525px) 100vw, 525px" /></figure></div>



<span id="more-598"></span>



<p>3. <a href="http://goo.gl/hb5xa">Atari Breakout</a><br>Atari&#8217;s famous 1978 hit Breakout is on google as well. To play this game, open google, type <em>Atari Breakout</em> and hit enter. Now switch the tab to google images and you&#8217;re there.</p>



<figure class="wp-block-image"><img data-recalc-dims="1" decoding="async" width="525" height="258" data-attachment-id="667" data-permalink="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/atari-breakout-google-game-2/" data-orig-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?fit=1294%2C635&amp;ssl=1" data-orig-size="1294,635" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="atari-breakout-google-game" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?fit=300%2C147&amp;ssl=1" data-large-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?fit=525%2C258&amp;ssl=1" src="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?resize=525%2C258" alt="atari-breakout-1978-hit" class="wp-image-667" srcset="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?resize=1024%2C503&amp;ssl=1 1024w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?resize=300%2C147&amp;ssl=1 300w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?resize=768%2C377&amp;ssl=1 768w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/atari-breakout-google-game-1.png?w=1294&amp;ssl=1 1294w" sizes="(max-width: 767px) 89vw, (max-width: 1000px) 54vw, (max-width: 1071px) 543px, 580px" /></figure>



<p>4.  <a href="https://www.google.com/doodles/halloween-2016">Google Halloween 2016 Google game</a><br>If you love halloween and cats this one of for you. This game has 5 levels and is really fun.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="522" height="286" data-attachment-id="602" data-permalink="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/google-halloween-2016-doogle-game/" data-orig-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?fit=522%2C286&amp;ssl=1" data-orig-size="522,286" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="google-halloween-2016-doogle-game" data-image-description="" data-image-caption="" data-medium-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?fit=300%2C164&amp;ssl=1" data-large-file="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?fit=522%2C286&amp;ssl=1" src="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?resize=522%2C286" alt="" class="wp-image-602" srcset="https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?w=522&amp;ssl=1 522w, https://i0.wp.com/abhishekg.com/blog/wp-content/uploads/2019/03/google-halloween-2016-doogle-game.png?resize=300%2C164&amp;ssl=1 300w" sizes="(max-width: 522px) 100vw, 522px" /></figure></div>
<p>The post <a href="https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/">Time killer and addictive Google Games</a> appeared first on <a href="https://abhishekg.com/blog">Abhishek G</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://abhishekg.com/blog/2019/03/time-killer-and-addictive-google-games/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">598</post-id>	</item>
	</channel>
</rss>
