DEV Community

Morcos Gad
Morcos Gad

Posted on • Updated on

Quick Tips - Laravel

Let's get started quickly and find some tips so I can share their fun with you.

You may assign multiple middleware to the route by passing an array of middleware names to the middleware method

Route::get('/profile', function () {
    //
})->middleware('auth');

Route::get('/', function () {
    //
})->middleware(['first', 'second']);
Enter fullscreen mode Exit fullscreen mode

Version Laravel 8 uses more requests help you with your project
https://laravel.com/docs/8.x/requests

$uri = $request->path();

if ($request->is('admin/*')) {
    //
}

if ($request->routeIs('admin.*')) {
    //
}

$url = $request->url();
$urlWithQueryString = $request->fullUrl();

$request->fullUrlWithQuery(['type' => 'phone']);

$method = $request->method();
if ($request->isMethod('post')) {
    //
}
Enter fullscreen mode Exit fullscreen mode

When assigning middleware, you may also pass the fully qualified class name

use App\Http\Middleware\EnsureTokenIsValid;

Route::get('/profile', function () {
    //
})->middleware(EnsureTokenIsValid::class);
Enter fullscreen mode Exit fullscreen mode

When assigning middleware to a group of routes, you may occasionally need to prevent the middleware from being applied to an individual route within the group. You may accomplish this using the withoutMiddleware method

use App\Http\Middleware\EnsureTokenIsValid;

Route::middleware([EnsureTokenIsValid::class])->group(function () {
    Route::get('/', function () {
        //
    });

    Route::get('/profile', function () {
        //
    })->withoutMiddleware([EnsureTokenIsValid::class]);
});
Enter fullscreen mode Exit fullscreen mode

The findOrFail method also accepts a list of ids

// Retrives the user...
$user = User::findOrFail(1);

// Throws a 404 because the user doesn't exist...
User::findOrFail(99);

// Retrives all 3 users...
$users = User::findOrFail([1, 2, 3]);

// Throws because it is unable to find *all* of the users
User::findOrFail([1, 2, 3, 99]);
Enter fullscreen mode Exit fullscreen mode

You can use value() method to get single column's value from the first result of a query

// Instead of
Integration::where('name', 'foo')->first()->active;

// You can use
Integration::where('name', 'foo')->value('active');

// or this to throw an exception if no records found
Integration::where('name', 'foo')->valueOrFail('active');
Enter fullscreen mode Exit fullscreen mode

Laravel 8.69 released with "Str::mask()" method which masks a portion of string with a repeated character

$userEmail = User::where('email', $request->email)->value('email'); // username@domain.com

$maskedEmail = Str::mask($userEmail, '*', 4); // user***************

// If needed, you provide a negative number as the third argument to the mask method
// which will instruct the method to begin masking at the given distance from the end of the string

$maskedEmail = Str::mask($userEmail, '*', -16, 6); // use******domain.com
Enter fullscreen mode Exit fullscreen mode

You can send e-mails to a custom log file
You can set your environment variables like this

MAIL_MAILER=log
MAIL_LOG_CHANNEL=mail
Enter fullscreen mode Exit fullscreen mode

And also configure your log channel

'mail' => [
    'driver' => 'single',
    'path' => storage_path('logs/mails.log'),
    'level' => env('LOG_LEVEL', 'debug'),
],
Enter fullscreen mode Exit fullscreen mode

Here we want to copy a column into the database

$post = Post::find(1);
$newPost = $post->replicate();
$newPost->created_at = Carbon::now();
$newPost->save();
Enter fullscreen mode Exit fullscreen mode

We want to know the method coming from a specific function or route use isMethod or method() to search for it

$request->isMethod('post');
in_array($request->method(),['POST','PUT','PATCH','DELETE']))
Enter fullscreen mode Exit fullscreen mode

Auto-Redirect to Login in Breeze or Jetstream

Route::redirect('/', 'login');
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code
Source :- https://www.youtube.com/watch?v=bnXauabSFYI
Source :- https://www.youtube.com/watch?v=YzBGmdnGtbY&t=83s
Source :- https://github.com/LaravelDaily/laravel-tips

Top comments (0)