Laravel features you may not know about

Introduction

Here are some features from Laravel that you may not be aware of. They're not exactly anything advanced or hidden, but I don't really notice that these functions get used or referenced very often. (Maybe they are though, and I've just not noticed it.)

Laravel tips and tricks that you might not know

Use the artisan down command to put the Laravel app down, but allow access to certain IP(s)

artisan down --allow=123.123.123.123

The php artisan down command is useful to use when you need to put your Laravel site down for maintenance or when upgrading the system. However, without using the --allow option you have no real way to test it as a regular user. To get around this you can provide a whitelist of IP addresses to allow.

You can also provide multiple IP addresses, or even IP ranges:

php artisan down --allow=127.0.0.1 --allow=192.168.0.0/16

Some other useful options for the down command include:

Screenshot of the message: "You can write anything here. It shows on the Laravel down page"

--message="something here"

You can provide a custom message to show users, by using the --message="..." option. This will show that message to your users while the site is down. You can modify it further by copying the 503.blade.php to your views dir. The default message is 'Sorry, we are doing some maintenance. Please check back soon.'.

php artisan down --message="You can write anything here"

--retry

You can set the retry value, which will be used for the Retry-After HTTP header's value.

php artisan down --retry=60

Need to do a query builder 'where' query on a couple of columns? Try this clean, one-method way:

Let's say you want to do the following SQL query:

<?php
    select * from `users`
    where
    `name` = 'some_name'
    and `email` = 'some_email'
    limit 1

You can achieve this with one 'where' method call. Eloquent will work out that the "and" in the middle means two seperate where clauses:

<?php
    \App\User::whereNameAndEmail('some_name','some@email')->first();
    // the above has the exact same result as:
    \App\User::where('name', 'some_name')->where('email', 'som@_email')->first();
    // also same as:
    \App\User::where(['name' => 'some_name', 'email' => 'some@email'])->first();

(change Name and Email as required - the important part is the And between them. Laravel will automatically work out what columns your where statement refers to)

And as well as "and", you can also do an "or" like this:

<?php
 \App\User::whereFooOrBar('foo value','bar value')->first();

Which will produce the following SQL query:

<?php
    select * from `users`
    where
    `foo` = 'foo value'
    or `bar` = 'bar value'
    limit 1
Eloquent's find() can accept multiple rows

You can use the query builder's find() method in the following way:

<?php
    $rows = SomeEloquentModel::find([1,4,6,11]);

If find() is passed an array, it will return a collection of Eloquent model rows with those IDs (of course, if those rows exist...).

Also applies to findOrFail(). They both (eventually) just call findMany() if passed an array of IDs to find.

Did you know that relations such as belongsTo can provide a default model if the relationship returns null?

I'm sure many others are aware of this, but I only found out about this very recently.

If you have a relation (a belongsTo, MorphOne or HasOne type), it might sometimes return null. In that case, you can provide a default with the withDefault() method.

It will automatically work out what type of object to return, but you can also set some default attributes.

Here are a few examples:

<?php
    public function user()
    {
    return $this->belongsTo('App\User')->withDefault();
    }
    //or
    public function user()
    {
    return $this->belongsTo('App\User')->withDefault([
    'name' => 'Guest Author',
    ]);
    }
    // or
    public function user()
    {
    return $this->belongsTo('App\User')->withDefault(function ($user) {
    $user->name = 'Guest Author';
    });
    }

For the implementation details check out SupportsDefaultModels.php.

Use the render() method on Exceptions to render a HTTP response to the user

If you run the following command:

php artisan make:exception --render SomeExceptionName

It will create a new exception class in your exceptions directory, with a blank render($request, Exception $exception) method.

If an exception is thrown and handled by your app/Exceptions/Handler.php file, it will check for method_exists($exception, 'render'). If it exists, it will call that method on the exception and return it to the user.

Here is an example of a render() method on an exception, which will return a view response:

<?php
    /**
    * Render the exception into an HTTP response.
    *
    * @param    \Illuminate\Http\Request
    * @return  \Illuminate\Http\Response
    */
    public function render($request)
    {
    response()->view('errors.custom.myexception', [], 500);
    }

You can use this method to return a response (such as a view) that will be displayed to the user.

Before I knew about this, I would hard code some logic in app/Exceptions/Handler.php when I needed to show a certain response to the user for a particular exception. It is much neater, in my opinion, to hard code it in the exception itself than to have a messy Handler.php file.

The cache's rememberForever($key, function() { return 'something'; }) function

If you use the cache feature, you almost certainly are doing something like this:

<?php
    $value = Cache::remember('users', Carbon::now()->addHour(), function () {
    return DB::table('users')->get();
    });

But did you know you can also do this:

<?php
    $value = Cache::rememberForever('users', function () {
    return DB::table('users')->get();
    });

This will get an item from the cache, or store the default value forever.

You can pass a file path to your route's group() to include that file

If your routes file is a bit messy, you can stick them in their own file and include the file with a call to group().

<?php
    Route::middleware(SomeMiddleware::class)
    ->group(__DIR__"/SomeGroup.php")

As far as I can tell this isn't mentioned in the docs (or I'm being blind at 1 AM and can't find it). Check out the group($callback) method on RouteRegistrar.

(You could just do a normal require() call as well...)

Eloquent: get a fresh version (fresh()) of the current model and duplicate rows (replicate())

Use ->fresh() to query the database and get a fresh version of the current item.

<?php
    $user = \App\User::first();
    $user->name = "Something new";
    $user = $user->fresh(); // note that it returns the fresh value, it doesn't affect the current model
    dump($user->name); // the original name, not 'something new'

If you want to rehydrate the existing model, then use refresh():

<?php
    $flight = App\Flight::where('number', 'FR 900')->first();
    $flight->number = 'FR 456';
    $flight->refresh();
    $flight->number; // "FR 900"

If you need to duplicate a Eloquent object, use:

<?php
    $new = SomeModel::first()->replicate();
    $new->save()

The replicate method lets you provide an array of attributes it should ignore when duplicating ($except=[]), for example:

<?php
    $new = User::first()->replicate(['password']); // replicate everything APART FROM the password attribute
    $new->save(); // $new will have all of the attributes as the first User row, but the 'password' attribute won't be there.
Some Routing static methods that are underused...
The main and commonly used routing methods...

There are 6 'main' routing methods (which almost every web app uses):

<?php
    Route::get($uri, $callback);
    Route::post($uri, $callback);
    Route::put($uri, $callback);
    Route::patch($uri, $callback);
    Route::delete($uri, $callback);
    Route::options($uri, $callback); // rarely used (apart from CORS?) in my experience

Plus the following (quite commonly used in my experience):

  • Route::match(['get', 'post'], '/', $callback); if you want the same URI to be available for

    multiple HTTP methods,

  • Route::any('foo', $callback); if you want any and all HTTP methods to apply for a route

All of the above, plus a few others such as Route::group(...) are pretty common. But there are a whole bunch of other very useful routing methods that I tend to not really notice very often. They include the following:

Redirecting URLs from within your routes file (web.php)

I've seen some pretty big Laravel projects that had half a dozen routes pointing to their own methods on a RedirectionController controller, that simply returned a redirection response. But you can redirect direct in the routes file:

<?php
    // if someone visits /here, they will get a HTTP redirect to /there
    Route::redirect('/here', '/there', 301); // 301 Moved Permanently

Note: the third param is optional, and it defaults to 302 (temporary) redirect.

Does your controller method just return a view? Skip the controller, return the view from the routes file...

If your controller's method is really simple and just returns a view, then you might be able to use the following:

<?php
    Route::view('/welcome', 'welcome'); // same as returning view("welcome") in a controller
    Route::view('/welcome', 'pages.welcome', ['name' => 'WebDevEtc']); // same as returning view("pages.welcome")->withName("WebDevEtc") in a controller
Route name prefixes

If you have a bunch of routes, you probably name each of them with things like:

<?php
 Route::get("/","BlogController@show")->name("blog.show"); 

You can avoid having to add the "blog." prefix to each name by using route name prefixes.

<?php
    Route::name('blog.')->group(function () {
    Route::get('show', function () {
    // Route assigned name 'blog.show'...
    })->name('show');
    });

I have to be honest, I'm not actually keen on this, as it makes searching for a route name a tiny bit more complicated, but it can clean up a busy routes file.

Fallback Routes

You can use Route::fallback(...), that will be used if no other routes matched. This is normally used to show a 404 error but can be useful in other situations as well.


Want to find more?

There are lots of methods not mentioned here when it comes to routing. Check out the documentation on laravel.com.

Use wildcard (*) checks for the current route

If you have some kind of navigation and want to add a class='active', you might be tempted to do something like if( request()->is('control-panel') || request()->is('control-panel/change-email') || request()->is('control-panel/edit-profile') { ... } to check the current URI (or passing an array to is()).

However, you can just use a wildcard:

<?php
    if (request()->is("control-panel*")) { ... }

You can use routeIs() in a similar way, but with the route name. (You can use this with the above tip (route name prefixes) to ensure that it always matches correctly.)

Auth::id() instead of Auth::user()->id

I see Auth::user()->id all of the time (and I had to admit that I do it myself quite a bit), but it is much quicker (to type) Auth::id() to get the ID of the user (or null if not logged in).

As pointed out on Reddit, rather than doing \Auth::user(), you can just do auth() and use the auth helper function. (Full example: auth()->id())

Simple Pagination

The normal pagination will count how many total rows there are and calculate the maximum number of pages. On large datasets, this isn't a good idea. The simple pagination option will only display a previous and next link and does a far quicker query on your database (as it doesn't need a full count of the number of rows).

You use it in the same way as the normal Laravel pagination, but just call simplePaginate() instead of paginate().

<?php
$users = DB::table('users')->simplePaginate(15);

Did you also know that it can output JSON with full pagination data?

<?php
    // ...
    {
        "total": 50,
        "per_page": 15,
        "current_page": 1,
        "last_page": 4,
        "first_page_url": "http://laravel.app?page=1",
        "last_page_url": "http://laravel.app?page=4",
        "next_page_url": "http://laravel.app?page=2",
        "prev_page_url": null,
        "path": "http://laravel.app",
        "from": 1,
        "to": 15,
        "data":[
            {
            // Result Object
            },
            {
            // Result Object
            }
        ]
    }

I recommend reading everything on the docs if you use pagination (which most of us do), as there are quite a few options when it comes to using the built-in pagination.

Laravel's tap() method

Although I've noticed this helper function being used quite a bit, I think it is underused, although I have to admit that I very rarely have used it myself. The tap($val, $callable) function is normally used in a way that lets you run the $callable function with the value of $val (i.e. it will run $callable($val)). Then, whatever the returned value of $callable, it will return $value.

Here is the source of the function, that will probably explain it better!

<?php
    /**
    * Call the given Closure with the given value then return the value.
    *
    * @param  mixed $value
    * @param  callable|null $callback
    * @return  mixed
    */
    function tap($value, $callback = null)
    {
    if (is_null($callback)) {
    return new HigherOrderTapProxy($value);
    }
    $callback($value);
    return $value;
    }

(The HigherOrderTapProxy part was added in a more recent version of Laravel - see this Laracasts for a great explanation video)

An example of where it is used is in the query builder in Laravel:

<?php
 // ...
    public function create(array $attributes = [])
    {
    return tap($this->newModelInstance($attributes), function ($instance) {
    $instance->save();
    });
    }

Of course, you could just do something like:

<?php
 // ...
    public function create(array $attributes = [])
    {
    $instance = $this->newModelInstance($attributes);
    $instance->save()
    return $instance;
    }

However, with the tap() function you can write cleaner code, turning multiple lines into nice one-liners.

Laravel News have a nice write up (better than the official docs so I recommend giving it a read.

Most of Artisan's make: commands will create files in subdirectories you tell it to (and will correctly namespace it)

The following will create the directory (if it does not already exist) /app/Models/, and place an empty model PHP file in it called YourModel.php, and it will be correctly namespaced (\App\Models):

php artisan make:model -m Models/YourModel

The command above will also create a migration file for you (thanks to the -m option).

Now the file will exist at app/Models/YourModel.php, and the migration file in your migrations directory.

Quickly log things with logger() and info()

Use info("log some info message") and logger("log a debug message"). It is slightly cleaner than app('log')->debug($message) or \Log::debug($message)...

Set model properties such as $perPage

Your Eloquent models almost certainly have properties such as: $fillable = ['title', 'description'], $casts = ['some_field'=>'array'] set.

BTW, if you don't know about $casts = ['some_property' => 'array', 'size_info'=>'object'] then check it out here. There are many options: integer, real, float, double, decimal (you can use it like: decimal:2 to have max of 2 digits), string, boolean, object, array, collection, date, datetime, and timestamp

However I rarely notice other properties set on models, including:

$perPage: Set the (default) number of rows per page, when you use Eloquent's pagination. Of course, you can override this in the pagination call.

<?php
    /**
    * The number of models to return for pagination.
    *
    * @var  int
    */
    protected $perPage = 15;

$incrementing: If you have a table without auto-incrementing ID rows then you will want to set the following to false:

<?php
// ...
    /**
    * Indicates if the IDs are auto-incrementing.
    *
    * @var  bool
    */
    public $incrementing = true;

$snakeAttributes: If a model's relationships have snake-casing enabled, Eloquent will snake case the keys so that the relation attribute is snake cased in the returned array to the developers.

<?php
    /**
    * Indicates whether attributes are snake cased on arrays.
    *
    * @var  bool
    */
    public static $snakeAttributes = true;
Eloquent Relationships: Only return models if they actually have a relationship row with has()

If you have two models, let's say BlogPost and Comment. They are linked by a OneToMany relationship. If you want to get all blog posts along with the comments you could do this:

<?php
 $postsWithComments = BlogPost::with("comments")->get();

However, this will return blog posts that have 0 comments. If you only want to get posts that have > 0 comments, you can do this (has()):

<?php
 $postsWithComments = BlogPost::with("comments")->has("comments")->get();
optional()

I have to admit that optional() is used very often, but I thought I'd just mention it anyway.

It accepts any value and lets you access properties (or call methods) on that method. If null was given then it will return null for any property or method call.

You use it like this:

<?php
    $a = null;
    $b = new Model();
    optional($a)->doSomething(); // null
    optional($a)->someProperty; // null
    optional($b)->doSomething(); // calls doSomething on the Model object
    optional($b)->someProperty; // the someProperty on the model object (if it exists)

It is useful when you don't know if something will have a value or not. I have used it in the past when dealing with an Eloquent row's relation - it might not exist. Rather than wrap some code in if/else, you can do something like this:

<?php
    $blogPost = BlogPost::first();
    echo "<div class='author_box'>"
        . optional($blogPost->author)->name
        . "</div>";

(simplified example... but it would either print the author name, or nothing)

Do you use View Composers?

View composers will bound data to a view every time that view file is rendered.

Or, to put another way: You can tell Laravel to send an array of parameters to a view, every time the view is rendered.

Let's say you had a alert.error view (resources/views/alerts/error.blade.php), and inside that you wanted a specific variable $error_prefix (some string - but the details don't matter here).

Inside a service provider:

<?php
    View::composer('dashboard', function (View $view) {
    $view->with(
    'error_prefix',
    'Some prefix that you needed in your blade file'
    );
    });

(You can also set up a whole composer class, and run View::composer('error_prefix', ErrorComposer::class), and within that ErrorComposer have a compose(View $view) method)

Use array_wrap() to ensure that you are working with an array

Sometimes you need to work with an array, but the supplied data might be a different data type - in which case you will want to wrap it in an array (it will be the single element in the array). This is simple to do:

<?php
    // could return an array, could return a string, etc. It could be anything
    $value = foo();
    if (!is_array($value)) {
    // if it turns out it isn't an array, wrap it in an array
    $value = [$value];
    }
    // now you can be sure you have an array, so do whatever you need:
    foreach($value as $row) { /* ... */ }

And although the snippet above could be simplified (and written on one line), it is a bit neater to use Laravel's helper function array_wrap()

<?php
    // could return an array, could return a string, etc. It could be anything
    $value = array_wrap(foo());
    // now you can be sure you have an array, so do whatever you need:
    foreach($value as $row) { /* ... */ }

More examples:

<?php
    $value = array_wrap(['a','b']); // ['a', 'b'] (no change)
    $value = array_wrap('asdf'); // ['asdf'] (wrapped the string in an array)
Eloquent: Add data to the output from toArray() (or toJson())

Let's say you have a User model, and you know that the user with ID of 1 is admin. When you do a toArray() or export it to JSON, you might want to output something to indicate if it is an admin. With a little bit of code you can get Eloquent to automatically add this.

You can do something like this:

<?php
    class User extends Model
    {
    // append the 'is_admin' attribute when doing toArray()/toJson()...
    protected $appends = ['is_admin'];
    // and this is where it will get that data from:
    public function getIsAdminAttribute()
    {
    // returns a bool, true if user.id === 1
    return $this->attributes['id'] === 1;
    }
    }

Note: This assumes that there was no is_admin column on the database table that this row came from. Otherwise it would have been included anyway.

You can also decide to append data at run time like this:

<?php
    return $user->append('is_admin')->toArray();
    // or
    return $user->setAppends(['is_admin'])->toArray();

See more here.

Pluralise strings with str_plural()

I think that this function is quite commonly used - it is quite a handy and useful function.

Sometimes you need to output something like "5 active posts" (plural), or "1 active post" (singular). You can write some quick if/else logic (or use the ternary operator) and handle it that way. Or use str_plural().

<?php
    $my_bottles = [1,2,3];
    echo "I have " . count($my_bottles). " " . str_plural('bottle', count($my_bottles));
    $your_bottles = [1];
    echo "You have " . count($your_bottles). " " . str_plural('bottle', count($your_bottles));

The above would output 'I have 3 bottles' (plural!) and 'You have 1 bottle' (singular!). The function handles uncountable words (see the Pluralizer class) such as 'sheep', 'software' so you won't end up with 'sheeps' and 'softwares'. But of course it isn't perfect so you should always check it works correctly with your input. And it only handles English words correctly. I did assume that there might be some extensions to this function to support other languages, but I was unable to find any.

There is also the opposite function: str_singular()

<?php
    $singular = str_singular('cars');
    // car
    $singular = str_singular('children');
    // child
Automatically fire events in your Eloquent models

There are a bunch of events that happen in your eloquent objects:

  • retrieved
  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted
  • restoring
  • restored

If you have an event (for example /app/Events/ContactWillBeDeleted.php), you might want to fire it when the 'deleting' eloquent event is fired. To easily to this, add ContactWillBeDeleted to your model's $dispatchesEvents array. See the example:

<?php
    protected $dispatchesEvents = [
    'deleting' => \App\Events\ContactWillBeDeleted::class,
    ];

How this specific example works: When you run Eloquent's delete() method, it runs the following code:

<?php
    if ($this->fireModelEvent('deleting') === false) {
    return false;
    }

(The return false part isn't relevant, but might be interesting to be aware of)

The fireModelEvent($event, $halt = false) method (see here) will then eventually call $this->fireCustomModelEvent(...).

fireCustomModelEvent() runs the following code (i've rewritten it, but it does the same thing for the purposes of this explanation. See here for the actual implentation):

<?php
    /** @var  string */
    $eventClassType = $this->dispatchesEvents[$event]; // remember, this was 'deleting' => \App\Events\ContactWillBeDeleted::class, so if $event was 'deleting' then $eventClassType === \App\Events\ContactWillBeDeleted::class
    /** @var  object */
    $eventObj = new $eventClassType($this); // this is now an instance of \App\Events\ContactWillBeDeleted in our example
    // static::$dispatcher is an instance that implements \Illuminate\Contracts\Events\Dispatcher
    // i.e. it is the event dispatcher
    static::$dispatcher->$method($eventObj); // this is where it fires the event

($method will be either 'until' or 'dispatch'. See the comment on the fireModelEvent method, or look at Dispatcher.php for details - see here)

To see how this works in more detail, see this line in Eloquent/Concerns/HasEvents.php.

Use URL::signedRoute() to make Laravel verify a URL has not been modified since it was created

Laravel allows you to easily create "signed" URLs to named routes. These URLs have a "signature" hash appended to the query string which allows Laravel to verify that the URL has not been modified since it was created. Signed URLs are especially useful for routes that are publicly accessible yet need a layer of protection against URL manipulation.

For example, you might use signed URLs to implement a public "unsubscribe" link that is emailed to your customers. To create a signed URL to a named route, use the signedRoute method of the URL facade:

<?php
use Illuminate\Support\Facades\URL;
    return URL::signedRoute('unsubscribe', ['user' => 1]);

If you would like to generate a temporary signed route URL that expires, you may use the temporarySignedRoute method:

<?php
    use Illuminate\Support\Facades\URL;
    return URL::temporarySignedRoute(
    'unsubscribe', now()->addMinutes(30), ['user' => 1]
    );

You must remember to validate. You can either do this it in your controllers by calling hasValidSignature:

<?php
    Route::get('/unsubscribe/{user}', function (Request $request) {
    if (! $request->hasValidSignature()) {
    abort(401);
    }
    // ...
    })->name('unsubscribe');

Or you can add the Illuminate\Routing\Middleware\ValidateSignature middleware to your route.

<?php
    Route::post('/unsubscribe/{user}', function (Request $request) {
    // ...
    })->name('unsubscribe')->middleware('signed');

(This is used by Laravel when creating the email verification link (see here)


New things, added 2021 - for anyone who has read this article before, here are the new and updated parts that have been updated/sent in from readers:
Use Pagination's onEachSide(5) to define how many links either side of the current page are displayed

If you use the very useful and handy ->paginate($per_page) method on the Eloquent Query Builder (to help generate pagination links), you might sometimes wish you could easily set how many links to show each side of the 'current' page.

Well, now you can with the very easy to use and understand onEachSide() method.

<?php
    $posts = BlogPost::paginate(15)->onEachSide(2);
Use withCount('relation_name') to get the count(*) for a relation

If you have the following code in your class:

<?php
    class BlogPost extends Model {
    function comments() {
    return $this->hasMany(Comment::class);
    }
    }

And given a BlogPost object, you can find out how many comments it has with:

<?php
    $blogPosts = BlogPosts::withCount('comments')->get();
    foreach($blogPosts as $blogPost) {
    echo $blogPost->comments_count;
    }

For more details see here

Use action() to generate a URL to a controller's action

If you know that you have a controller named BlogViewController, with a method show, you could execute the following to get a clickable link:

<?php
    $url =  action(
    'BlogViewController@show',
    ['id' => $blogPost->id]
    );
    echo '<a href="' . $url . '">View post</a>';
    // or the following way:
    $url_alternative = action(
    [BlogViewController::class, 'show'],
    ['id'=>$blogPost->id]
    );
    echo '<a href=' . $url_alternative .'>View post</a>';

If there is no action in your routes that matches that controller/method, then you will get a InvalidArgumentException exception thrown.

View details here.

Use Blade Components/slots, Component Aliases and Include Aliases

Blade's Components are a feature that are similar to how you use sections and extending layouts. They are meant to be used for commonly used parts of your layout, and use the $slot variable for the content that you wish to inject into it.

Here is an example of a defining a component (notice the $slot variable that is echoed out):

<?php
<!-- /resources/views/alert.blade.php -->
    <div class="alert alert-danger">
        {{ $slot }}
    </div>

And here is how to use it:

<?php
@component('alert')
    Uh oh! A bad error just occurred!
    @endcomponent

This would return output similar to:

<?php
    <div class="alert alert-danger">
        Uh oh! A bad error just occurred!
    </div>

If this doesn't make sense, then you could think of the @component part as working similar to the following:

<?php
    @include('alert', ['slot'=>'Uh Oh! A bad error!'])
Blade Component Aliases:

The component files don't have to reside in the base directory of resources/views - it works like normal blade views (so you could call @component('layouts.components.alert') ...

However, if they reside in a subdirectory (like the example in the previous paragraph, which lives in resources/views/layouts/components) you may wish to alias it. In the boot() method of AppServiceProvider you can add the following:

<?php
    use Illuminate\Support\Facades\Blade;
    Blade::component('layouts.components.alert', 'alert');

Then you can just refer to it as @component('alert')...

Include Aliases

This could be included as it's own item on this list, but it work in a similar way as blade component aliases.

If your Blade includes are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a Blade include that is stored at resources/views/includes/input.blade.php with the following content:

<?php
<input type="{{ $type ?? 'text' }}">

In AppServiceProvider's boot method, you could add the following:

<?php
Blade::include('include.input', 'input');

Then you can use that view (via it's alias) with:

<?php
@input(['type' => 'email'])
Include a view in Blade for every item in an array (or collection) with @each

If you have an iterable list (such as an array or a Laravel collection), you might wish to include a view for each item:

<?php
        @foreach(BlogPost::all() as $blogPost)
            @include('blogposts.loop', ['post'=>$blogPost])
        @endforeach

But a much cleaner way to do this is:

<?php
        @each('blogposts.loop', 'blogPost', 'post')

Take note of where I used 'post', 'blogPost' in both examples.

If you like to use

<?php
            @forelse($rows as $row)
                {{ $row->name }}
            @empty
                Sorry, nothing found
            @endforelse

(which will run a foreach, but if it has nothing to loop through it will go to the 'empty' section)

Well, you can do something similar with the each directive (errors.none_found in the example below is a blade file):

<?php
        @each('blogposts.loop', 'blogPost', 'post', 'errors.none_found')
An important thing to note: When you use @each, the views do not share or have access to any other variables from the parent view. If they need access to those, then you should use the normal @foreach, along with regular @include.
View::first([...]) to return the first view from an array that exists (and Blade's @includeFirst([...]) similar directive)

Both of these work in a similar way. If you have an array, such as ['actions.something_specific','actions.default'] (assuming that you are hoping that resources/views/actions/something_specific.blade.php exists, but you know that resources/views/actions/default.blade.php exists), you could do the following to try and show the something_specific view first, but falling back to the default one if not.

<?php
    // in some controller:
    $data = ['message' => 'something here'];
    return view()->first(
    ['actions.something_specific','actions.default'], $data
    );

Or to do the same thing in a blade file:

<?php
        @includeFirst(['actions.something_specific','actions.default'], $data)

(This could also be achieved by checking if View::exists('actions.something_specific') returns true)

Some other useful blade directives to check out:

  • @includeIf('view_name', ['some'=>'data']) - include the view if it exists
  • @includeWhen($boolean_value, 'view_name', ['some'=>'data']) - include the view if the first param ($boolean_value) is true
Injecting services into your blade files, from within a blade file

Say you have a service SomeCoolService, and you wish to call it's someFunction method inside blade.

You could use a view composer to set it up so you send a SomeCoolService to that view. Or, you could do everything from within your blade files:

<?php
        @inject('someCoolService', 'App\Services\SomeCoolService')
        <div>
            Monthly Revenue: {{ $someCoolService->someFunction() }}.
        </div>
Use the fluent dump() method within your chained Collection calls

If you are sorting and filtering a Collection, you might do something like this during debugging:

<?php
    $collection = collect(['John Doe', 'Jane Doe'])
    ->filter($some_filtering_func);
    // check what is in the collection
    dump($collection);
    $collection->map($some_mapping_func);

But there is a method on the Collection class called dump that can make it a bit cleaner:

<?php
    $collection = collect(['John Doe', 'Jane Doe'])
    ->filter($some_filtering_func)
    ->dump($collection) // <<
    ->map($some_mapping_func);

Obviously, don't use this in production.

Use Form::open with a route param, even if there are parameters for that route (Form::open(['route' => ['route.name.here', 'param-here']))

This is not part of the core Laravel code, but from the Laravel Collective Form package. I use this package on almost all (non API) Laravel projects, it is very common so I'm including it here

This isn't going to save much time or make anything easier to read, but it always annoyed me a little that you could do Form::open() with a parameter named 'route', but it only worked when a route had no required route parameters.

However, you can call it! Just put it in an array (as the title of this section shows)

<?php
        {{ Form::open( [ 'route' => ['route.name', $post->id] ] }}
        {{-- same as: --}}
        {{ Form::open( [ 'url' => route('route.name', $post->id) ] }}
Other Laravel Collective's Form Snippets

While I'm on the topic of this useful package, some other small snippets that might be interesting:

<?php
        // see the action() function I mentioned above:
        {{ Form::open(['action' => 'Controller@method']) }}
        // Get the form CSRF token (automatically added when you use Form::open()
        {{ Form::token() }}
        // Form model binding - this is the same as calling
        // Form::setModel($user) then calling Form::open([..])
        {{ Form::model($user, ['route' => ['user.update', $user->id]]) }}

And one really useful feature relating to Form::model() are form model accessors.

If you use the Form::model opener, you might wish to define how some attributes are used. You can set what it will use by using the FormAccessible trait, and setting an accessor method called formNameAttribute($value) method (of course, change the method name to something that matches your attributes).

<?php
    // your model
    class BlogPost extends Model {
    use Collective\Html\Eloquent\FormAccessible;
    // this will only be called for items within the Form::model()
    public function formNameAttribute($value)
    {
    return strtoupper($value);
    }
    }

I don't want to write too much about something that isn't part of the core Laravel code, so for a full example and a better explanation please visit the official docs.

Laravel's Dump Server

Note: this was removed in a recent Laravel version but kept here as it was an intereesting feature. You can still install it at https://github.com/beyondcode/laravel-dump-server

This isn't really a hidden or secret feature of Laravel - it is very well publicised. However, it is quite new so there might be some developers who haven't used it.

Run php artisan dump-server.

Then every time your code encounters a dump(...) or dd(...) call, it won't be displayed in the request but will appear in your terminal (where the php artisan dump-server command is running).

This can be a huge time saver when debugging with APIs and webhooks.

Just don't forget that it is running and get confused why your dd() calls are showing a blank page!

Custom if statements in Blade

In your AppServiceProvider's boot method you can add the following:

<?php
    Blade::if('env', function ($environment) {
        return app()->environment($environment);
    });

Then inside your blade files you can just use @env('production') ...@elseenv('testing') ...@endenv

Change 'env' to whatever you wish!

Use the prepareForValidation() in your Form Requests

If you wish to modify data from a Form Request object before validation, you can use the prepareForValidation() method.

The prepareForValidation() method is called before validation happens, and if your request calls a method such as $this->merge(['some_key'=>'a new value']) then when you later call something like $request->all(), it will contain an item with key 'some_key' and value 'a new value'.

<?php
    public function prepareForValidation()
    {
    $this->merge(
    [
    'name' => $this->get('first_name') . ' ' . $this->get('last_name'),
    'email' => strtolower($this->get('email')),
    'random_position' => rand(0,100),
    ]
    );
    }

Source: here

Some other useful functions in Requests

Here is a quick overview of some methods that you may not be aware of on the main Request class. Some are quite common, most are obvious what they do just from the method name. There are many that I've not included, so I recommend you check out the Request class yourself.

(I will refer to it as Request::something(), but you will probably very often use it as $request->something() if you type hint a Request parameter in your controllers. If you use it exactly as it is below, remember to add Use Request (or prepend the calls below with a slash))

Request::create()

Request::create(...) is useful when you need to create a request (I use it in testing sometimes). Here is how to set it up:

<?php
    $created = Request::create(
    '/forum/thread/123', // url
    'POST', //method
    ['reply_body' => 'Some reply to a thread'], // attributes
    [ /* cookies */ ],
    [ /* files */ ],
    [ /* server */ ],
    null /* content */
    );

To see more about this check out the source here)

Request::method()

Request::method() (alias for Request::getMethod() will return an uppercase string of the method ('GET', 'POST', 'PUT', etc). Because of limitations in browsers when it comes to HTTP requests (only being able to do GET/POST), Laravel 'fakes' the DELETE, PATCH (etc) requests. If you want to find the 'real' request (either GET or POST) then you can use getRealMethod().

Request::fullUrl()

Request::fullUrl() returns the full url ('http://yoursite/segment1/seg2')

Request::segment()

Request::segments() returns an array of all the segments for the request path. You can also use Request::segment(3,'some-optional-default') to get the third segment (or provide a default if it does not exist)

Request::path()

Request::path() returns the path (so for this request: /)

Request::ajax()

Request::ajax() and Request::isXmlHttpRequest(): Both of these return true if the request is a XMLHttpRequest. It determines this by checking for the X-Requested-With header, which is set by almost all JS libraries that make new XmlHttpRequests. Also related: Request::pjax() which checks for the X-PJAX header. I have never heard of this - I think it relates to this.

Request::hasPreviousSession()

Request::hasPreviousSession() - returns a boolean value that indicates if the request contains a Session which was started in one of the previous requests.

Request::getClientIp()

Request::getClientIp() returns the first IP from Request::getClientIps(), which itself returns an array of IP addresses. The first IP from getClientIps() is the 'most trusted' one. Unless a request is coming via a proxy of some kind, you will probably only have one IP in getclientIps()

Request::getUserInfo()

Request::getUserInfo() has nothing to do with Laravel's authenticated user. This is part of the Symfony Request class, and will return what is effectively $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'], which gets it's values from Basic HTTP Authentication. See here.

Ok, that's it!

I'm almost certain that most Laravel developers will be aware of a bunch of the above tips (maybe all of them). Almost all of the above tips were directly in the official docs. But maybe some people will find a new feature of Laravel from the list above.

Whenever I start a new language, framework or library I always try and skim through the documentation, use it, then give it a full read. I'm sure I quickly forget most of what I read, but there are always lots of features in big libraries/frameworks which are underused.

Please let me know in the comments if there are any useful features of Laravel that you think are underused, that I've not mentioned. I'm sure there are tons!

Comments Laravel features you may not know about