6
Php

Laravel 3 Helper Functions

Laravel is a clean and classy framework for PHP web development and I’m getting familiar with it and I’m really loving it. Well, Laravel has it’s nice documentation for everything but I didn’t find any documentation on it’s helper functions and I didn’t understand why they didn’t provide any documentation for those really helpful helper functions. Often I use those helper functions to save some code and time so I’ve decided to write about those helper functions so maybe someone else can use those functions without digging in to the code.

These helper functions are located in the laravel/helpers.php file and there are many useful functions but I’ll discuss about some of them, specially all of the array related functions and few other, those I really love to use.


Function : array_get

Description : Returns the specified element from an array using dot notation. This function takes three parameters, the first one is the array from which you want to get the item, the second one is the array key that you want to get and the third parameter is optional that will be returned if the specified is not found.

Example :

/**
 * Get an item from an array using "dot" notation.
 *
 * @param  array   $array
 * @param  string  $key
 * @param  mixed   $default
 * @return mixed
 */
$array = array(
   'user' => array(
       'name' => 'Heera',
       'phone' => '+88 01717542608'
   )
);
echo array_get($array, 'user.name', 'Not Given'); // Heera

Function : array_set

Description : Appends/Sets an item in to the specified array using dot notation. This function takes three parameters, the first one is the array to which you want to set/append the new item, the second one is the array key and the third parameter is the value for that key.

Example :

/**
 * Set an array item to a given value using "dot" notation.
 *
 * @param  array   $array
 * @param  string  $key
 * @param  mixed   $value
 * @return void
 */
$array = array(
   'user' => array(
       'name' => 'Heera',
       'phone' => '+88 01717542608'
   )
);
array_set($array, 'user.age', '35');
echo array_get($array, 'user.age'); // 35

Function : array_forget

Description : Remove an array item from a given array using “dot” notation. This function takes two parameters, the first one is the array from which you want remove the item and the second one is the array key that you want to remove.

Example :

/**
 * Remove an array item from a given array using "dot" notation.
 *
 * @param  array   $array
 * @param  string  $key
 * @return void
 */
$array = array(
   'user' => array(
       'name' => 'Heera',
       'phone' => '+88 01717542608'
   )
);
array_forget($array, 'user.phone');
print_r($array); // Array ( [user] => Array ( [name] => Heera ) )

Function : array_first

Description : Returns the first element in an array which passes a given truth test. This function takes three parameters, the first one is the array from which you want get the first item and the second parameter is a closure (anonymous function) that will check for the given value and will return the first matched array item and the third one is optional that will be returned if specified value is not found.

Example :

/**
 * Return the first matched element from an array.
 *
 * @param  array    $array
 * @param  Closure  $callback
 * @param  mixed    $default
 * @return mixed
 */
$array = array(
   'user' => array(
       'name' => 'Heera',
       'phone' => '+88 01717542608'
   )
);
$look_for = 'Heera';
$matched_item = array_first($array, function($k, $v) use($look_for) {
    return $v == $search_value;
}, 'Not Given');
echo $matched_item // Heera
// or
$matched_item = array_first($array, function($k, $v) {
    return $v == 'Nothing'; 
}, 'Not Given'); 
echo $matched_item // Not Given

Function : array_strip_slashes

Description : Recursively removes slashes from array keys and values and returns a new array. This function takes only one parameter and it is the array that you want to remove slashes from.

Example :

/**
 * Recursively remove slashes from array keys and values.
 *
 * @param  array  $array
 * @return array
 */
$array = array(
    '\name' => '\Heera',
    'age' => '35'
);
$new_array = array_strip_slashes($array);
print_r($new_array); // Array ( [name] => Heera [age] => 35 )

Function : array_divide

Description : Divides an array into two arrays. One with keys and the other with values and returns one new array of two arrays. This function takes only one parameter and it is the array that you want to divide the keys and values in two different arrays.

Example :

/**
 * Divide an array into two arrays. One with keys , one with values.
 *
 * @param  array  $array
 * @return array
 */
$array = array(
    'name' => 'Heera',
    'age' => '35'
);
$new_array = array_divide($array);
print_r($new_array); // Array ( [0] => Array ( [0] => name [1] => age ) [1] => Array ( [0] => Heera [1] => 35 ) )

Function : array_pluck

Description : Pluck an array of values from an array. This function takes two parameters, the first one is the array that you want to pluck array item from and other one is the array key that you want to pluck and it returns another plucked array of values.

Example :

/**
 * Pluck an array of values from an array
 *
 * @param  array   $array
 * @param  string  $key
 * @return array
 */
$array = array(
    'user' => array(
        'name' => 'Heera',
        'phone' => '+88 01717542608'
    )
);
$new_array = array_pluck($array, 'name');
print_r($new_array); // Array ( [user] => Heera )
// or
$array = array(
    'user' => (object) array(
        'name' => 'Heera',
        'phone' => '+88 01717542608'
    )
);
$new_array = array_pluck($array, 'name');
print_r($new_array); // Array ( [user] => Heera )

Function : array_only

Description : Get a subset of the items from the given array. This function takes two parameters one is the array, from which you want to get another subset of arrays and the other one is the array keys, those you want to apart and get as a subset of the original array.

Example :

/**
 * Get a subset of the items from the given array.
 *
 * @param  array  $array
 * @param  array  $keys
 * @return array
 */
$array = array(
    'name' => 'Heera',
    'age' => '35',
    'phone' => '+88 01717542608'
);
$new_array = array_only($array, array('name', 'age'));
print_r($new_array); // Array ( [name] => Heera [age] => 35 )

Function : array_except

Description : Get all of the given array except for a specified array of items. This function takes two parameters one is the array, from which you want to get array items and the other one is the array keys, those you don’t want to get from the original array, just opposite of the array_only function.

Example :

/**
 * Get all of the given array except for a specified array of items.
 *
 * @param  array  $array
 * @param  array  $keys
 * @return array
 */
$array = array(
    'name' => 'Heera',
    'age' => '35',
    'phone' => '+88 01717542608'
);
$new_array = array_except($array, array('phone'));
print_r($new_array); // Array ( [name] => Heera [age] => 35 )

Function : head

Description : Returns the first element of an array. This function takes only one parameter and that is the array, from which you want to retrieve the first element. This is simply a convenient wrapper around the reset method, you can do the same thing using echo reset($array);.

Example :

/**
 * Return the first element of an array.
 *
 * This is simply a convenient wrapper around the "reset" method.
 *
 * @param  array  $array
 * @return mixed
 */
$array = array(
    'total' => '100',
    'user' => array(
        'name' => 'Heera',
        'phone' => '+88 01717542608'
    )
);
echo (head($array)); // 100
// or just using underlying code of the head function
echo reset($array); // 100

Function : eloquent_to_json

Description : Transforms Eloquent models to a JSON object. This function takes only one parameter and that is the Eloquent|array model, which you want to transform into a JSON object.

Example :

/**
 * Transform Eloquent models to a JSON object.
 *
 * @param  Eloquent|array  $models
 * @return object
 */
$user = User::find(23); // 23 is user id from my users table
echo eloquent_to_json($user); // {"id":23,"username":"mrtutor",...}
// or
$user = User::find(23); // 23 is user id from my users table
$json = eloquent_to_json($user);
$decoded_json = json_decode($json, true);
echo $decoded_json['username']; // mrtutor

Function : starts_with

Description : Determines if a given string begins with a given value. This function takes two parameters, first one is the string, in which you want to look up the string/value and the second one is the value, which you want to check if it is at the beginning of the given string.

Example :

/**
 * Determine if a given string begins with a given value.
 *
 * @param  string  $haystack
 * @param  string  $needle
 * @return bool
 */
$name = 'Sheikh Heera';
$first_name = 'Sheikh';
if(starts_with($name, $first_name))
{
    echo 'First Name : ' . $first_name; // First Name : Sheikh
}

Function : ends_with

Description : Determine if a given string ends with a given value. This function takes two parameters, first one is the string, in which you want to look up the string/value and the second one is the value, which you want to check if it is at the end of the given string, just opposite of the starts_with function.

Example :

/**
 * Determine if a given string ends with a given value.
 *
 * @param  string  $haystack
 * @param  string  $needle
 * @return bool
 */
$name = 'Sheikh Heera';
$last_name = 'Heera';
if(ends_with($name, $last_name))
{
    echo 'Last Name : ' . $last_name;
}

Function : str_contains

Description : Determines if a given string contains a given sub-string. This function takes two parameters, first one is the string, in which you want to look up the sub-string and the second one is the sub-string, which you want to check if it is available in the given string.

Example :

/**
 * Determine if a given string contains a given sub-string.
 *
 * @param  string        $haystack
 * @param  string|array  $needle
 * @return bool
 */
$str = 'I\'m from Bangladesh';
$find = 'Bangladesh'; 
// or
$find = array('country' => 'Bangladesh');
if(str_contains($str, $find))
{
	echo 'Asian'; // Asian
}

Function : str_finish

Description : Cap/Adds a string with a single instance of the given string. This function takes two parameters, first one is the string, in which you want to cap/add another string at the end and the second one is the string, which you want to add at the end of the main/first string.

Example :

/**
 * Cap a string with a single instance of the given string.
 *
 * @param  string  $value
 * @param  string  $cap
 * @return string
 */
echo str_finish('Sheikh Heera', ' (Developer)'); // Sheikh Heera (Developer)
//or
$user = array(
    'name' => 'Heera',
    'age' => '35',
    'phone' => '+88 01717542608',
    'role' => 'Developer'
);
echo str_finish(head($user), ' (' . array_get($user, 'role') . ')' ); // Sheikh Heera (Developer)

Function : get_file_size

Description : Calculate the human-readable file size (with proper units). This function takes only one parameter and it’s the int value of bytes and it outputs the human readable format of the size using proper units, for example, if you give the parameter 1024 (as byte) then it’ll output 1KiB.

Example :

/**
 * Calculate the human-readable file size (with proper units).
 *
 * @param  int     $size
 * @return string
 */
echo get_file_size(1024); // 1 KiB
echo get_file_size(6000000); // 5.72 MiB

There are other useful and very handy helper functions available in Laravel that we can use often and these are:

e($value); 
// Shortcut of HTML::entities($value);
__($key, $replacements = array(), $language = null)
// Shortcut of Lang::line($key, $replacements, $language);
url($url, $https);
// Shortcut of URL::to($url, $https)
asset($url, $https);
// Shortcut of URL::to_asset($url, $https)
action($action, $parameters);
// Shortcut of URL::to_action($action, $parameters)
route($name, $parameters);
// Shortcut of URL::to_route($name, $parameters)
view($view, $data = array());
// Shortcut of View::make($view, $data = array())
render($view, $data = array());
// Shortcut of View::make($view, $data)->render()
render_each($partial, $data, $iterator, $empty); 
// Shortcut of View::render_each($partial, $data, $iterator, $empty)
yield($section) 
// Shortcut of Section::yield($section)

Also another handy and most useful helper function in Laravel is dd($value); which is very useful for debugging the code, it is a two in one function because it works as dump and die. There is no need to explain about this function, I believe every Laravel developer use this function more than any other function during the development of any project. I hope, this writing will be helpful to other and also it would be a good idea to dig in to the source code, reading the source code will definitely help us to learn new tips and tricks, it doesn’t matter how expert you are, you will get new ideas.

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]

0
Php

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]