My Laravel Snippets

I’ve been developing, confidently and fluently I should add, with Laravel for a year or so now and I’ve picked up some interesting tips and tricks along the way. As a self taught developer, it’s always been fun to learn something new, apply it and see that it works. The biggest draw and perk of being a developer, to me, is the instant results of your hard work.

As a note, these were tested with Laravel 5.5 and above, the exception being the first trick which works in 5.7 and above (if I recall correctly).

 

Blade Templating: Short IF/ELSE

In PHP, we have shorthand IF/ELSE operators, in Blade, it’s even more simple and easy to visualize:

{{ $variable ?? "Variable is empty!" }}

This will output $variable (if it exists and has a value). If it doesn’t, it’ll output “Variable is empty!” To me, this is a super simple and efficient way of handling variable empty checks in Blade.

 

Request Validation: Multiple check boxes

The Request validation system is very powerful and handy. It also cuts out a TON of code from the controller when implemented correctly. At one time, I had multiple check boxes on a form and I needed to ensure at least one was checked. Cue the array validation rule:

public function rules()
{
    return [
        'mybox_array' => 'required|min:1'
    ];
}

 

Friendly Debugging

Sometimes you need to see what’s going on and what’s being passed around. The dd() function is a useful way of doing just that. It cuts out having to var_dump() with the <pre>tags wrapped around it. You can use this with Eloquent queries, simple variables and arrays. It’s also usable inside of a Blade template or in a controller.

For blade: {{ dd($variable) }}
For controllers: dd($variable);

 

Blade Templating: Checking if user is valid

We have access to the Auth facade in Laravel’s controllers and templates. What many of us do to check if the user is authenticated is the following:

@if (auth()->user()) {
   //User is authenticated
@elseif
   //User is NOT authenticated
@endif

When used in multiple places within the same template, it gets crowded. Instead, I use the short version:

@auth
   //User is authenticated
@endauth

 

Eloquent: Working with dates

I struggle with date related queries in native SQL, but having realized the power of the whereDate methods with Laravel’s Eloquent queries, I feel like it’s increased my ability a lot.

Get specific date's info: Car::whereDate('purchased', '3/25/2019')->get();
Get data between two dates: Car::whereBetween('purchased', ["3/25/2019", "4/01/2019"]);

In addition to those, there are a few more methods you can use for working with dates:

whereYear(), whereMonth(), whereDay(), whereTime()

Each of the above taking in two parameters; a column name and a valid date.

adam Written by:

Be First to Comment

Leave a Reply