Developer Snippet Diary

Helpers, Custom helpers

Helpers - Laravel - Documentaion

1. Predefined Helpers

1. add use class if important IE For some string helpers

use Illuminate\Support\Str;

2. Run helper in controller or view

public function index(){
	echo Str::of('Hello, world!')->wordCount(); // 2
}

Some more str helpers are 

$string = Str::ucfirst('foo bar'); // first charter capital
$string = Str::upper('laravel'); // convert string to upper case 
echo e('<html>foo</html>');  // htmlspecialchars  with the double_encode option set to true // &lt;html&gt;foo&lt;/html&gt;
$result = Str::endsWith('This is my name', 'name'); // true
$matches = Str::is('foo*', 'foobar'); // true
$plural = Str::plural('car'); // cars // converts a singular word string to its plural form. This function currently only supports the English language:

2. Make your own helper

we need it when we need it at multiple places ie multiple controller and views

1. create a new file helpers.php inside app directory

<?php
 function printVariable($var){
	echo $var."<br/>";
 }
?>

2. modify composer.json

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
		"files":["app/helpers.php"]
    },

3. Run command in main directory

composer dump-autoload // all project files optimize

4. Run your helper in controller or view

 public function index(){
		$data="indexpage run";
		printVariable($data);
	}
Posted by: R GONDAL
Email: rizikmw@gmail.com