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
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
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
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 theFacades
prefix.)
'aliases' => [
…
'Json' => Facades\App\Helpers\Json::class,
]
1
2
3
4
2
3
4
- In the console, execute the following commands:
php artisan clear-compiled
php artisan ide-helper:generate
1
2
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
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
2
3
4
5
6
- Download JSON Formatter for Chrome to make JSON easy to read
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
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
2
3
4
- In the console, execute the following commands:
php artisan clear-compiled
php artisan ide-helper:generate
1
2
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
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="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>
1
2
3
4
5
6
7
8
9
10
11
12
13
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
2
3
4