Handy Laravel Tips

Laravel has a lot of handy features what hidden in the documentation or not documented at all. We collected a few features what helped our work, but not everyone knows them.

@auth – @guest

Almost every web app has to authenticate users. Also, we want to show/hide things based on the user’s authentication status. The most popular solution was to check the user status with the Auth facade in an if blade directive:

@if (Auth::check())
    You are logged in!
@else
    You are a guest!
@endif

Now the framework provides a blade directive for this. With the @auth directive, we don’t need to use the @ifAuth::check() combo. Also, it provides the chance to check the user with different guards.

@auth
    You are logged in!
@endauth

@auth('api')
    Check with API guard!
@endauth

@guest
    You are a guest!
@endguest

@lang

With the trans() function we can translate our strings. Usually, in our blade files, we wrap the function in the {{  }} block, then print the result. The framework provides a directive to make it easier.

{{ trans('auth.failed') }}

@lang('auth.failed')

Not a huge thing, but still, it keeps your app a little bit cleaner and understandable!

$with

Eager loading is one of the most used features of Eloquent. The point is, we can reduce the number SQL queries with ‘loading’ our relationships. We can use the with() or the load() methods on our model to fetch the desired results.

Post::with('comments')->get();

$post = Post::first();
$post->load('comments');

But it’s very possible; we want to load a relationship whenever we use the model. In this case, we can add a property to our model, and define the relationships we want to load.

// App\Post.php

/**
 * The relationships to eager load with the model.
 * 
 * @var array
 */
protected $with = [
    'comments',
];

If your model uses a relationship often, this solution can keep your controllers a bit cleaner, while you don’t need to worry about eager loading anymore.

$withCount

Like the $with property above, we can use eager load our relationships. But in this case, we load the number of the given relationships, and not the results itself.

Of course, we can use the withCount() method on our model, but if we need the number of the related models, we should consider to load them all the time.

// App\Post.php

/**
 * The relationships to eager load with the model count.
 * 
 * @var array
 */
protected $withCount = [
    'comments',
];