Laravel helpers

  • Laravel contains several helper functions: https://laravel.com/docs/7.x/helpers
    • Many of these functions are used by the framework itself but you can also use them in your own application
  • Sometimes it is also useful to write your own helper functions that you will often use in your application. We will write a helper function for the following examples:
    • In a controller, you fetch a dataset and then send it to a view. For debugging, it is useful to only show the dataset in JSON format.
    • You can write a helper function to mask an email address in the source code so that spam robots don't recognize the email address

Preparation

  • You only have to do these actions once!
  • Create a new folder app/Helpers
  • Create a service provider: php artisan make:provider HelperServiceProvider
  • Open the file app/Providers/HelperServiceProvider.php and paste the code below into the register function
    • The service provider loops over all the files that you create in the app/Helpers folder and will ensure that all these classes are automatically known by Laravel


 
 
 


public function register()
{
    foreach (glob(app_path('Helpers') . '/*.php') as $file) {
        require_once($file);
    }
}
1
2
3
4
5
6
  • Open the file config/app.php and load the service provider within the providers array


 


'providers' => [
    ...
    App\Providers\HelperServiceProvider::class,
]
1
2
3
4

Example 1: Json::dump()

  • Create a new PHP class Json.php in the app/Helpers folder
    (Right-click the Helpers folder and choose 'New > PHP class'. Always start a class with a capital letter.)
  • Paste the code below into Json.php:






 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


<?php

namespace App\Helpers;

class Json
{
    /**
     * Dump data as json (add ?json to URL)
     * Dump the given variable and ends execution of the script (add ?dd to URL)
     *
     * @param mixed $data string, array, associative array object
     * @param bool $onlyInDebugMode runs only in debug mode: default = true
     * @version 1.0
     */
    public function dump($data = null, $onlyInDebugMode = true)
    {
        $show = ($onlyInDebugMode === true && env('APP_DEBUG') === false) ? false : true;
        if (array_key_exists('json', app('request')->query()) && $show) {
            header('Content-Type: application/json');
            die(json_encode($data));
        } elseif (array_key_exists('dd', app('request')->query()) && $show) {
            dd($data);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  • Open the file config/app.php and add an alias to the aliases array. (Don't forget the Facades prefix.)


 


'aliases' => ['Json' => Facades\App\Helpers\Json::class,
]
1
2
3
4
  • In the console, execute the following commands:
php artisan clear-compiled
php artisan ide-helper:generate
1
2
  • An example of how you can use the function in a controller





 



// controller
public function index()
{
    $users = User::select('id', 'name', 'email')->orderBy('name')->get();
    $result = compact('users');
    Json::dump($result);
    return view('allusers', $result);
}
1
2
3
4
5
6
7
8
// allusers.blade.php
<ul>
    @foreach($users as $user)
        <li>{{ $user->name }}: <a href="mailto:{{ $user->email }}">{{ $user->email }}</a></li>
    @endforeach
</ul>
1
2
3
4
5
6

Json::dump()

Example 2: Mask::email()

To avoid spam, you should never leave the real email address in the source code. With a simple trick you can mask the mail address with unicode characters that a spam robot can't interpret, but a browser can.

  • The class we make here, is especially meant to be used within Blade!
  • Unicode for character a is decimal a or hexadecimal a
    https://unicodelookup.com/
  • Create a new helper-class App/Helpers/Mask.php
  • Include the following code:




 







































<?php

namespace App\Helpers;

use Illuminate\Support\HtmlString;

class Mask
{
    /**
     *  Obfuscate mail address
     * 
     * @param string $email
     * @param string $name
     * @return HtmlString
     */
    public function email($email, $name = null)
    {
        $name = $this->obfuscate($name ?: $email);
        $email = $this->obfuscate('mailto:' . $email);
        return new HtmlString('<a href="' . $email . '">' . $name . '</a>');
    }

    private function obfuscate($str)
    {
        $safe = '';
        foreach (str_split($str) as $char) {
            if (ord($char) > 128) {
                return $char;
            }
            switch (rand(1, 3)) {
                case 1:    // decimal
                    $safe .= '&#' . ord($char) . ';';
                    break;
                case 2:    // hexadecimal
                    $safe .= '&#x' . dechex(ord($char)) . ';';
                    break;
                case 3:
                    $safe .= $char;
            }
        }
        return $safe;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  • Open the file config/app.php and add an alias to the aliases array. (Don't forget the Facades prefix.)
'aliases' => ['Mask' => Facades\App\Helpers\Mask::class,
]
1
2
3
4
  • In the console, execute the following commands:
php artisan clear-compiled
php artisan ide-helper:generate
1
2
  • Look at the source code of the homepage. The mail address is not encrypted.
  • Add a second list to the homepage








 
 
 


// allusers.blade.php
<ul>
   @foreach($users as $user)
       <li>{{ $user->name }} : <a href="mailto:{{ $user->email }}">{{ $user->email }}</a></li>
   @endforeach
</ul>
<hr>
<ul>
   @foreach($users as $user)
       <li>{{ $user->name }}: {{ Mask::email($user->email)  }}</li>
   @endforeach
</ul>
1
2
3
4
5
6
7
8
9
10
11
12
  • Look at the result in the browser. Nothing has changed?
  • Now look at the source code in the browser
<ul>
    <li>ITF User 0: <a href="mailto:itf_user_0@mailinator.com">itf_user_0@mailinator.com</a></li>
    <li>ITF User 1: <a href="mailto:itf_user_1@mailinator.com">itf_user_1@mailinator.com</a></li>
    <li>ITF User 10: <a href="mailto:itf_user_10@mailinator.com">itf_user_10@mailinator.com</a></li>
    ...
</ul>
<hr>
<ul>
    <li>ITF User 0: <a href="&#x6d;a&#x69;&#x6c;t&#x6f;&#58;&#105;t&#x66;&#x5f;&#117;&#x73;&#101;&#x72;&#x5f;0&#64;&#109;&#x61;&#105;&#108;&#x69;n&#x61;&#116;&#x6f;&#x72;&#x2e;&#x63;o&#109;">&#105;t&#102;_&#117;s&#101;&#114;&#x5f;0@&#x6d;&#x61;&#x69;&#108;i&#x6e;at&#111;&#114;&#x2e;&#99;&#x6f;m</a></li>
    <li>ITF User 1: <a href="m&#97;i&#x6c;&#116;&#x6f;:itf&#95;u&#x73;&#101;r_&#49;&#64;&#x6d;&#97;il&#105;&#110;&#x61;tor&#x2e;&#99;o&#x6d;">i&#x74;&#x66;_&#x75;&#115;&#101;&#114;&#x5f;&#x31;@m&#97;&#105;&#108;&#x69;&#x6e;&#x61;&#x74;&#x6f;&#114;&#46;&#99;&#111;m</a></li>
    <li>ITF User 10: <a href="m&#x61;&#x69;&#108;&#116;o&#58;&#105;&#116;f&#x5f;&#117;&#115;&#101;&#x72;&#95;&#49;&#x30;&#64;&#109;&#x61;i&#108;&#105;n&#x61;&#116;&#111;&#x72;&#46;&#x63;&#x6f;&#x6d;">i&#116;&#x66;&#x5f;&#117;&#x73;er&#95;&#x31;&#x30;@&#109;a&#x69;&#108;&#x69;&#110;at&#111;r&#x2e;c&#111;&#x6d;</a></li>
    ...
</ul>
1
2
3
4
5
6
7
8
9
10
11
12
13

Assignment: Mask::tel() and Mask::sms()

  • Create two extra methods to mask a tel-link and an sms-link.
<p>{{ Mask::tel('+32479123456', 'call me') }}</p>
<p>{{ Mask::tel('+32479123456') }}</p>
<p>{{ Mask::sms('+32479123456', 'text me') }}</p>
<p>{{ Mask::sms('+32479123456') }}</p>
1
2
3
4
Last Updated: 10/21/2021, 8:59:57 AM