Miscellaneous Helpers

Available Methods

Method Listing

abort()

The abort function throws a HTTP exception which will be rendered by the exception handler:

abort(401);

You may also provide the exception's response text:

abort(401, 'Unauthorized.');

abort_if()

The abort_if function throws an HTTP exception if a given boolean expression evaluates to true:

abort_if(! Auth::user()->isAdmin(), 403);

abort_unless()

The abort_unless function throws an HTTP exception if a given boolean expression evaluates to false:

abort_unless(Auth::user()->isAdmin(), 403);

auth()

The auth function returns an authenticator instance. You may use it instead of the Auth facade for convenience:

$user = auth()->user();

back()

The back() function generates a redirect response to the user's previous location:

return back();

bcrypt()

The bcrypt function hashes the given value using Bcrypt. You may use it as an alternative to the Hash facade:

$password = bcrypt('my-secret-password');

byte_converter()

The byte_converter method converts one byte type into another byte type.

$megabytes = byte_converter('3072', 'KB', 'MB');

// 3MB

$kilobytes = byte_converter('1024', 'B', 'KB');

// 1KB

cache()

The cache function may be used to get values from the cache. If the given key does not exist in the cache, an optional default value will be returned:

$value = cache('key');

$value = cache('key', 'default');

You may add items to the cache by passing an array of key / value pairs to the function. You should also pass the number of minutes or duration the cached value should be considered valid:

cache(['key' => 'value'], 5);

cache(['key' => 'value'], Carbon::now()->addSeconds(10));

collect()

The collect function creates a collection instance from the given array:

$collection = collect(['taylor', 'abigail']);

config()

The config function gets the value of a configuration variable. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. A default value may be specified and is returned if the configuration option does not exist:

$value = config('app.timezone');

$value = config('app.timezone', $default);

The config helper may also be used to set configuration variables at runtime by passing an array of key / value pairs:

config(['app.debug' => true]);

convert_to_bytes()

The convert_to_bytes method converts a human readable file size to bytes. If the byte format is not provided, it'll be presumed as bytes.

$fileSize = convert_to_bytes('3MB');

// 3145728

dd()

The dd function dumps the given variables and ends execution of the script:

dd($value);

dd($value1, $value2, $value3, ...);

If you do not want to halt the execution of your script, use the dump function instead:

dump($value);

dispatch()

The dispatch function pushes a new job onto the Laravel job queue:

dispatch(new App\Jobs\SendEmails);

env()

The env function gets the value of an environment variable or returns a default value:

$env = env('APP_ENV');

// Return a default value if the variable doesn't exist...
$env = env('APP_ENV', 'production');

event()

The event function dispatches the given event to its listeners:

event(new UserRegistered($user));

factory()

The factory function creates a model factory builder for a given class, name, and amount. It can be used while testing or seeding:

$user = factory(App\User::class)->make();

friendly_byte()

The friendly_byte method convert bytes to a human readable format.

$fileSize = friendly_byte('5242880');

// 5MB

human_filesize()

The human_filesize method returns the passed bytes in a human readable format.

$filesize = human_filesize(1030000);

// 1.03 MB

info()

The info function will write information to the log:

info('Some helpful information!');

An array of contextual data may also be passed to the function:

info('User login attempt failed.', ['id' => $user->id]);

logger()

The logger function can be used to write a debug level message to the log:

logger('Debug message');

An array of contextual data may also be passed to the function:

logger('User has logged in.', ['id' => $user->id]);

A logger instance will be returned if no value is passed to the function:

logger()->error('You are not allowed here.');

method_field()

The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:

<form method="POST">
    {{ method_field('DELETE') }}
</form>

now()

The now function creates a new Illuminate\Support\Carbon instance for the current time:

return now();

old()

The old function retrieves an old input value flashed into the session:

$value = old('value');

$value = old('value', 'default');

optional()

The optional function accepts any argument and allows you to access properties or call methods on that object. If the given object is null, properties and methods will simply return null instead of causing an error:

return optional($user->address)->street;

{!! old('name', optional($user)->name) !!}

redirect()

The redirect function returns a redirect HTTP response, or returns the redirector instance if called with no arguments:

return redirect('/home');

return redirect()->route('route.name');

render_markdown()

The render_markdown method compiles the given markdown string into HTML.

$html = render_markdown('# Hello World!');

// <h1>Hello World!</h1>

report()

The report function will report an exception using your exception handler's report method:

report($e);

request()

The request function returns the current request instance or obtains an input item:

$request = request();

$value = request('key', $default = null)

response()

The response function creates a response instance or obtains an instance of the response factory:

return response('Hello World', 200, $headers);

return response()->json(['foo' => 'bar'], 200, $headers);

retry()

The retry function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, it's return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown:

return retry(5, function () {
    // Attempt 5 times while resting 100ms in between attempts...
}, 100);

session()

The session function may be used to get or set session values:

$value = session('key');

You may set values by passing an array of key / value pairs to the function:

session(['chairs' => 7, 'instruments' => 3]);

The session store will be returned if no value is passed to the function:

$value = session()->get('key');

session()->put('key', $value);

tap()

The tap function accepts two arguments: an arbitrary $value and a Closure. The $value will be passed to the Closure and then be returned by the tap function. The return value of the Closure is irrelevant:

$user = tap(User::first(), function ($user) {
    $user->name = 'taylor';

    $user->save();
});

If no Closure is passed to the tap function, you may call any method on the given $value. The return value of the method you call will always be $value, regardless of the what the method actually returns in its definition. For example, the Eloquent update method typically returns an integer. However, we can force the method to return the model itself by chaining the update method call through the tap function:

$user = tap($user)->update([
    'name' => $name,
    'email' => $email
]);

today()

The today function creates a new Illuminate\Support\Carbon instance for the current date:

return today();

value()

The value function's behavior will simply return the value it is given. However, if you pass a Closure to the function, the Closure will be executed then its result will be returned:

$value = value(function () {
    return 'bar';
});

view()

The view function retrieves a view instance:

return view('auth.login');