CategoryLaravel

VIN validation – Laravel custom validation rule

Working on a project involving dealerships and cars, I needed a way to validate car VIN (Vehicle Identification Number) so I came up with a custom Laravel validation rule.

Continue reading

Gainslog now makes daily backups to Google Drive

Thanks to this great tutorial on how to extend Laravel’s storage to Google Drive, Gainslog now pushes daily updates to Google Drive.

Following the tutorial, one issue people run into is a File not found error when running the backup command.

You can get around it by setting the backup folder name to an empty string – but that will place all the backup zip files directly into the storage/app folder.

One way to make sure all backups go into a single folder is to setup a new local disk inĀ filesystem.php and update the backup.php config to use that one instead.

'local' => [ 
    'driver' => 'local', 
    'root' => storage_path('app')
], 
'local-backups' => [ 
    'driver' => 'local', 
    'root' => storage_path('app/backups')
]

And then in config/backup.php

'destination' => [

    /*
     * The filename prefix used for the backup zip file.
     */
    'filename_prefix' => 'backup-',

    /*
     * The disk names on which the backups will be stored.
     */
    'disks' => [
        'local-backups',
        'google'
    ],
]

Eloquent trick #1: Replace conditionals with “when”

It happens very often that we want to apply certain eloquent query conditions based on what a request sends in. Sometimes it’s a “search by name” thing, other times we just need to filter the records based on a status column.

Usually it looks like this:

public function index(Request $request) 
{
    $posts = Post::newQuery();

    if ($request->term) {
        $posts->where('name', 'LIKE', "%{$request->term}%");
    }

    if ($request->status) {
        $posts->where('status', $request->status);
    }

    return view('posts.index', ['posts' => $posts->paginate()])
}

I recently discovered there’s an alternative to using conditionals. The “when” method executes a callback (second parameter) when the first parameter evaluates to true.

public function index(Request $request) 
{
    $posts = Post::when($request->term, function($q, $term) {
        $q->where('name', 'LIKE', "%{$term}%");
    })->when($request->status, function($q, $status) {
        $q->where('status', $status);
    });

    return view('posts.index', ['posts' => $posts->paginate()])
}

It’s not all that better if you ask me. Yes, it hides the conditionals, but it also makes the code harder to read. Especially if you have more conditions to add.

I’d use this “when” approach for single conditions only.

public function index(Request $request) 
{
    $posts = Post::when($request->term, function($q, $term) {
        $q->where('name', 'LIKE', "%{$term}%");
    });

    return view('posts.index', ['posts' => $posts->paginate()])
}

© 2019 cdruc

Theme by Anders NorénUp ↑