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:
class Json
{
    /**
     * Dump data as json (add ?json 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));
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  • 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('name', 'email')->take(3)->get();
    $result = compact('users');
    Json::dump($result);
    return view('home', $result);
}
1
2
3
4
5
6
7
8
// home.blade.php
<ul>
    @foreach($users as $user)
        <li>{{ $user->name }} : <a href="{{ $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








 
 
 


// home.blade.php
<ul>
   @foreach($users as $user)
       <li>{{ $user->name }} : <a href="{{ $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>Eline Jacob : <a href="eline.jacob@mailinator.com">eline.jacob@mailinator.com</a></li>
    <li>Noa Renard : <a href="noa.renard@mailinator.com">noa.renard@mailinator.com</a></li>
    <li>Ferre Lemmens : <a href="ferre.lemmens@mailinator.com">ferre.lemmens@mailinator.com</a></li>
</ul>
<hr>
<ul>
    <li>Eline Jacob: <a href="m&#x61;il&#x74;&#x6f;&#x3a;&#101;l&#x69;ne&#46;&#106;&#x61;&#x63;o&#x62;&#x40;&#109;&#x61;&#105;&#x6c;&#x69;&#x6e;&#97;&#x74;or.c&#x6f;&#109;">eli&#x6e;&#x65;&#x2e;&#106;&#x61;c&#x6f;&#98;&#x40;m&#x61;&#x69;l&#105;na&#x74;&#x6f;r.&#99;&#x6f;&#x6d;</a></li>
    <li>Noa Renard: <a href="&#x6d;ail&#116;o&#58;&#x6e;&#111;&#x61;&#x2e;&#x72;&#x65;&#x6e;ar&#x64;&#x40;m&#97;i&#108;&#105;nat&#111;&#114;&#46;&#99;o&#109;">&#x6e;o&#x61;&#x2e;&#114;&#x65;n&#x61;&#114;&#x64;&#64;&#109;&#x61;il&#105;nato&#x72;.&#x63;om</a></li>
    <li>Ferre Lemmens: <a href="m&#x61;&#105;&#108;&#116;&#x6f;:&#x66;e&#x72;re.le&#109;m&#x65;&#110;&#115;&#x40;&#x6d;a&#x69;&#x6c;&#x69;n&#97;&#x74;&#111;r&#x2e;co&#109;">&#102;&#101;rre.&#108;&#x65;&#x6d;men&#x73;@m&#x61;ili&#110;&#97;&#x74;&#111;r&#x2e;&#99;&#x6f;m</a></li>
</ul>
1
2
3
4
5
6
7
8
9
10
11

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: 6/5/2020, 8:02:06 AM