Laravel Tricks

View Routes

There is no need to create a separate view controller if you only need to return a view.


Route::view('/my-page', 'my.blade.template', ['foo' => 'bar']);

The view method accepts a URI as its first argument and a view name as its second argument. In addition, you may provide an array of data to pass to the view as an optional third argument:

https://laravel.com/docs/5.6/routing#view-routes

Use Stacks

At first you my think that Stacks are the same as an @inlcude, but that not true. As the name reveals you can call the stack multiple times, where a include you will only get the last value.

// first component
@push('scripts')
    <script src="/my-script.js"></script>
@endpush

// ...somewhere else in your codes
@push('scripts')
    <script src="/tinymce.js"></script>
@endpush

In your layout.blade.php

<head>
    @stack('scripts')
    <!-- -Will return: -->
    <script src="/my-script.js"></script>
    <script src="/tinymce.js"></script>
</head>

https://laravel.com/docs/5.6/blade#stacks

Testing if config does exist

Use the default value from the config-helper instead of checking for not null.


// Instead of
if(config('app.config') != null) {

}

// ...use the default value
if (config('app.config', false)) {

}

now() helper

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


$inOneYear = now()->addYear()->diffForHumans();