How To Concatenate & Interpolate Strings In Twig

Twig is arguably the most powerful, modern and easy to use templating engine in PHP.

When using twig, sooner or later, you will run into the situation where you need to join two strings (concatenation) or evaluate an expression in strings (interpolation). Please consider the following

Concatenate Strings In Twig

To join two strings in Twig, you can use the tilde ~ operator as follows

{{ "Welcome Mr " ~ name }}

This will give the output Welcome Mr JohnDoe if the value of the name variable is JohnDoe.

You can play with this exact example on the twig playground.

Interpolating Strings In Twig

Sometimes you will desire to evaluate an expression and embed the result in a string, this is called interpolation, consider the example below where we will like to display the total sales of two months and display it.

{{ "Jan & Feb Sales = #{jan_sales + feb_sales}"}}

This will give the output “Jan & Feb Sales = 51” if the values of jan_sales and feb_sales are 28 & 23 respectively.

You can play with this exact example on the twig playground.

How to add a new PostgreSQL version to Laragon

To achieve this, follow the steps listed below

  1. Download the zip archive of the postgresql version you wish to install from (https://www.enterprisedb.com/download-postgresql-binaries).
  2. Save it and extract it to your laragon path > bin > postgresql folder, usually this will be (c:\laragon\bin\postgresql\).laragon-folder
  3. This is the most important part, backup your postgresql data folder and then rename the folder, so that there is no folder (c:\laragon\data\postgresql).
  4. Initiate the database cluster to the location (C:\laragon\data\postgresql) using the command below
       initdb -D c:\laragon\data\postgresql --encoding=UTF8
    

     

  5. Once the operation in step (4) succeeds, then run laragon and select the new version of laragon and start it.laragon-select-new-version

Quick snippet – Selecting only certain columns for a model in laravel

With a model named (Person) that maps to a table named (persons) with a structure defined below

CREATE TABLE `persons` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(255) NOT NULL,
  `last_name` VARCHAR(255)  NOT NULL,
  `email` VARCHAR(255) NOT NULL,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `persons` (`email`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Then, Consider the eloquent statement given below

$result = Person::find(1);

this is equivalent to,

SELECT * FROM Persons

The above can be wasteful if all you require is just a few columns such as the firstname and lastname, to fix this, we use the eloquent statement below

$result = Person::find(1, ['first_name', 'last_name']);

This is equivalent to,

SELECT first_name, last_name FROM persons

Hope, you have been able to learn something new today.

Introduction to Logical Shift And Its Use Cases

If like me, you have a degree in computer science, you must have encountered logical shifts during the course of your academic studies, if not, if you have learnt pretty much any programming language, you would have encountered them. The issue is that most people treat them as something to be aware of but not really understood. If you give me a couple of minutes, I hope to help simplify it to you.

What is logical shift

Logical shift is a type of bitwise operation that shifts/moves the bits in its operands in a particular direction. In simple terms, if you logically shift X by Y, it means that the operation will move the bits in X by Y positions. Still sounds geeky, let us break it down together.

There are two types of logical shifts, namely

  1. Right Shift (denoted by >> )
  2. Left Shift (denoted by << )

If you consider the definition above, Right shift means that the bits in (X) would be shifted to the right by Y places, also Left shift means that the bits in (X) would be shifted to the left by Y places.

Example of Left Shift

let X = 4 and Y = 2, lets find X << Y

Convert X  to binary, then you have

X = 100  (i.e. the binary representation of 4 is 0000 0100 )

Note: you should use the 8 digits representation

If you find the binary calculation confusing, please read up about it here.

Now, to calculate (X << Y), i.e we move the bits in X  to the left by 2 places.

  1. before move X = 0000 0100
  2. after left move (1) , X = 0000 1000
  3. after leftmove (2) , X = 0001 0000

Now we convert (0001 0000) back to decimal and we have 2.

Hence, 4 << 2  == 16.

Example of Right Shift

let X = 8 and Y = 2, lets find X >> Y

Convert X  to binary, then you have

X = 1000  (i.e. the binary representation of 8 is 0000 1000).

Now, to calculate (X >> Y), i.e we move the bits in X to the right by 2 places.

  1. before move X = 0000 1000
  2. after right move (1) , X = 0000 0100
  3. after right move (2) , X = 0000 0010

Note: since the first 4 digits in the binary value of X is (0) and we are shifting to the right, we could have discared it and just used (1000).

Now we convert (0010) back to decimal and we have 2.

Hence, 8  >> 2  is equal to 2.

Use cases of logical shifts (both left and right).

Left shift (<<) is used to multiply a value by any power of 2 and Right bit shift (>>) is used to divide by any power of two. consider the table below

Cheatsheet or Ways of calulating the logical shifts faster

The left logical shift (<<) is the same as

Left Bit Shift
# Operation X Y Resolution Result
1 X << Y 8 2 8 * pow(2,2) 32
2 X << Y 2 4 2 * pow(2,4) 32
3 X << Y 3 2 3 * pow(2,2) 12

and,

Right Bit Shift
# Operation X Y Resolution Result
1 X >> Y 64 4 64 / pow(2,4) 4
2 X >> Y 4 2 4 / pow(2,2) 1
3 X >> Y 8 2 8 / pow(2,2) 2

So, that is all. Hope i have made the use of logical shift alot clearer to you.

giphy1

Did you know? You can fetch multiple Eloquent records with one command

The Eloquent class in Laravel has a method called find, this you must be aware of , you can use this to find an Eloquent Model record using the primary key. This is used as follows

// Retrieve a model record by its primary key...
$car = App\Car::find(1);

Now, what if we want to find all cars with primary key in the list [1,2,3]? You can suppluy an array of primary keys to the find method or use the findMany method. Consider the code snippet below

$cars = App\Car::find([1, 2, 3]);
or
$cars = App\Cr::findMany([1, 2, 3]);

 

Note: If you supply an array of keys to the find method, it calls findMany internally. Whichever you decide to use between the two methods described above, they both return an instance of  \Illuminate\Database\Eloquent\Collection.

giphy5

 

 

Highlighting Active Bootstrap Menu Items (Nav – Item) Based On Route

In this post, I will show you a niifty little trick, one that is always required whenever you are working on some sort of web project with multiple routes.

You occasionally need to set the nav-item that inidicates the current route to be active (i.e. make it coloured ), to achieve this using laravel, consider the code snippet below

<ul class="navbar-nav">
<li class="nav-item {{ is_active('route.name.one') }}">
    <a class="nav-link" href="{{ route('route.name.one') }}">Route One</a></li>
<li class="nav-item {{ is_active('route.name.two') }}">
    <a class="nav-link" href="{{ route('route.name.two') }}">Route Two</a></li>
<li class="nav-item {{ is_active('route.name.three') }}">
    <a class="nav-link" href="{{ route('route.name.three') }}">Route Three</a></li>
</ul>

As you can see from the snippet displayed above, for every <li> element, the is_active function call has been added to class attribute , this function takes the name of a route as its argument and it returns a class name (active) if the current route name matches that which was supplied. Consider the snippet below to see the logic in the function stored in a file called helpers.php in a new folder called custom (note:  you can store your helper file anywhere you deem logical, I have just chosen custom/helpers.php).


if (!function_exists('is_active')) {
    /**
     * @param string $routeName
     * @param string $activeClassName
     *
     * @return string
     */
    function is_active(string $routeName, string $activeClassName = 'active')
    {
        $result = '';
        if (request()->route()->getName() === $routeName) {
            $result = $activeClassName;
        }

        return $result;
    }
}

How do you make your function available globally?

To make the function in the [core/helpers.php] file available globally, you need to autoload it using the files attribute of the composer.json file as follow.

"autoload": {
    "classmap": [
      "database/seeds",
      "database/factories"
    ],
    "psr-4": {
      "App\\": "app/"
    },
    "files": [
      "core/helpers.php"
    ]
  }

Hope you have found this helpful..

How to extend the laravel Collection with a macro

At this point in time, if you are familiar with the Laravel framework, I am sure you must have used the lovely Collections class. It is one of my favourite features of the laravel framework, so much so that I use in some bespoke projects outside laravel.

What is Laravel Collections?

It is nothing but php arrays on steroids. It allows you to perform very cool manipulations and processing of php arrays.

How do you create a collection?

$collectionInstance = collect([1,2,3,4,5,6,7]);

$collectionInstance2 = \Illuminate\Support\Collection::make([1,2,3,4,5,6,7]);

The collection class has a hosts of methods , such as

  1. avg
  2. sum
  3. unique
  4. and a lot more

However, sometimes you wish to use a method on the collection class and it isn’t available, so how do you do it? Collection Macros to the rescue.

Creating a macro to convert all items of a collection to camel case.

Consider, if you wish to convert all the strings in a collection to their respective camel case values, and there isn’t one method to do this. Obviously you can use a map or transform to achieve this, but for convenience sake, lets create a macro.

 Collection::macro('camelise', function(){
    return $this->map(function ($value) {
        return camel_case($value);
     });
 });

// to use it
$items = ['foo_bar', 'hello_world'];
$expectedValues = ['fooBar', 'helloWorld'];
$camelValues = collect($items)->camelise();

// assert that result matches the expected values.
$arraysAreEquals = $expectedValues === $camelValues->toArray();
assert($arraysAreEquals);

 

Where do I put the macros?
As helpful as this is, imagine if you have a 100 of such methods, where do you keep them?

Now this is a subjective answer, you can extract your methods into files and require them from a loop of the glob of the location of these files or you create a class with your macros and you use the Php Reflection Class to loop through them and add them to the Collection class.

Also, the AppServiceProvider will be a good point to add the logic described above.

 

giphy4

Fetching Laravel Eloquent results ordered by oldest to newest

In the previous post, I showed you how to order you results from newest to oldest using Eloquent model.

It is only logical to show you how to reverse the operation, ordering you results from the oldest to the newest. As always, Laravel in its majesty has already created a method for this and guess what it is called? oldest, so obvious right?

Consider the code below

Post::oldest()->get();

This will return the results already ordered by created_at from oldest to newest.

giphy3

Fetching Laravel Eloquent results order by newest to oldest

This tiny requirement is one that keeps popping up in you day to day programming routine, yet it is greatly misunderstood at least in the laravel way.

Imagine, if you have a model called Post (mapped to table named posts) and you have been asked to list the posts in descending order of creation date (created_at). Solving this using the ever reliable raw sql can be done as follows

select * from posts order by created_at desc

Wrong way

A very forgivable but wrong approach is to get the Posts and then order It

 Post::get()->sortByDesc('created_at');

While this would work, it is inefficient and in some cases may even be wrong, it is mainly inefficient because it fetches then entire Posts results before ordering it. This may be very expensive as you can imagine depending on the size of the posts table.

Right way (Long route)

The right way is to add the ordering condition on the Post model before getting it. i.e

 Post::orderBy('created_at', 'desc')->get();

As you can see, this is different from the wrong way because it orders the resultset before getting it.

Right way (Short route)

Although we have a right way of achieving this using the method described above, laravel is known for syntactic sugar and guess what, there is one for doing just this. It is called latest. Consider the code below

 Post::latest()->get();

giphy2

Quick primer- How to evaluate strings to boolean in PHP

Occasionally in PHP, you need to evaluate a string value to its boolean counterpart. One very common example of when this is needed is when you try to represent boolean in query string parameters. The jury is still out on the most appropriate way to represent a boolean value in Rest API or a query string, some of the

  1. true
  2. True
  3. TRUE
  4. false
  5. FALSE
  6. Yes
  7. No
  8. On
  9. Off
  10. 0
  11. 1

all of the values listed above are valid ways to represent a boolean value in your API or query string hence the need find a valid way to change the values correctly to their boolean value.

Evaluation using filter_var()

this filter_var method has been present in PHP since php5 and as the name implies, it filters a variable with a specified filter, for the purpose of this writeup, we are interested only in the boolean filter which is named FILTER_VALIDATE_BOOLEAN.

check the example below

filter_var("1", FILTER_VALIDATE_BOOLEAN)   // => bool(true)
filter_var("on", FILTER_VALIDATE_BOOLEAN)  // => bool(true)
filter_var("false", FILTER_VALIDATE_BOOLEAN) // => bool(false)

Value (int) BoolVal Boolean
1 1 TRUE
 0 0 FALSE
true 1 TRUE
false 0 FALSE
1 1 TRUE
0 0 FALSE
1 1 TRUE
0 0 FALSE
on 1 TRUE
off 0 FALSE
yes 1 TRUE
no 0 FALSE
True 1 TRUE
FalSe 0 FALSE