Create Custom helper and use their function in laravel 6

helper

Helper is a very useful file and most using to globally function defined and it’s used every place you want to like in your project.

Laravel includes a variety of global “helper” PHP functions. Many of these functions are used by the framework itself; however, you are free to use them in your own applications if you find them convenient.

So, let start our tutorial

Step 1: Changes in composer.json

Open your composer.json file and put the below code.

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/Http/helper.php"
        ]
    },

Now open your terminal and put below code:

composer dump-autoload

Step 2: Create a function in a helper file

Create helper.php file in app/Http folder

function notificationMsg($text, $message){
	\Session::flash($text, $message);
}

These function I was already created in my previous tutorial Notification message show using a toastr in laravel 6.


Step 3: Changes in Controller.

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;

class UserController extends Controller{
    public function index(Request $request){
    	$data = User::orderBy('id','DESC')->paginate(5);
        return view('Admin.users.index',compact('data'));
    }
    public function create(){
    	$roles = Role::pluck('name','name')->all();
    	return view('Admin.users.create',compact('roles'));
    }
    public function store(Request $request){
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|same:confirm-password'        
        ]);
        $input = $request->all();
        $input['password'] = Hash::make($input['password']);
        $user = User::create($input);

        notificationMsg('success', "User Created Successfully!");
        return redirect()->route('users.index');
    }

So Our tutorial was ready, now please follow the previous tutorial for how to use the helper function and follow these tutorial to make custom helper function.


Now, open your tutorial and put the below URL:

http://localhost:8888/users

My biggest fear is when my brain stops thinking. So keep thinking and big thinking. Happy Coding!

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!