10 Laravel Quick Tips

10 quick laravel tips
Spread the love

Tip 1. Controllers Having Single Action

In some situations you need a single action in a controller, if this is the case in Laravel you can achieve it by __invoke() method.

<?php

namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;

class ShowProfile extends Controller
{
   /**
   * Show the profile for the given user.
   *
   * @param int $id
   * @return Response
   */
    public function __invoke($id)
    {
         return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

Routes:

Route::get('user/{id}', 'ShowProfile');

Artisan command to generate this controller:

php artisan make:controller ShowProfile --invokable

Tip 2. Migration Fields Having Timezone

Do you know in Laravel migrations are just not limited to timestamps() you can also add timestampsTz()

Schema::create('employees', function (Blueprint $table) {
 $table->increments('id');
 $table->string('name');
 $table->string('email');
 $table->timestampsTz();
});

Also, there are columns dateTimeTz() , timeTz() , timestampTz(), softDeletesTz().

Tip 3. Eloquent has() deeper

You can use Eloquent has() function to query relationships even two layers deep!

// Author -> hasMany(Book::class);
// Book -> hasMany(Rating::class);
$authors = Author::has('books.ratings')->get();

Tip 4. SoftDeletes: Restore Multiple

To restore soft deleted rows, you can restore them in one sentence.

User::withTrashed()->where('author_id', 1)->restore();

Tip 5. Image Validation

During image upload, validate images on specific dimensions.

'photo' => 'dimensions:max_width=4096,max_height=4096'

Tip 6. Wildcard Subdomains

You can create route group by dynamic subdomain name, and pass its value to every route.

Route::domain('{username}.workspace.com')->group(function () {
 Route::get('user/{id}', function ($username, $id) {
 //
 });
});

Tip 7. Route::view() – If controller is not needed

In some cases you just want to return view instead of mapping a key to controller method, that can be achieved by Route::view()

// Instead of this
Route::get('about', 'TextsController@about');
// And this
class TextsController extends Controller
{
 public function about()
 {
 return view('texts.about');
 }
}
// Do this
Route::view('about', 'texts.about');

Tip 8. More Easy dd

You can directly do dd() on collection by following code.

// Instead of
$users = User::where('name', 'Taylor')->get();
dd($users);
// Do this
$users = User::where('name', 'Taylor')->get()->dd();

Tip 9. Quick orderBy on create_at

Instead of:

User::orderBy('created_at', 'desc')->get();

You can do it quicker:

User::latest()->get();

By default, latest() will order by created_at

Tip 10. More events after user registration

Want to perform some actions after new user registration? Head to
app/Providers/EventServiceProvider.php and add more Listeners classes, and then in those classes implement handle() method with $event->user object

class EventServiceProvider extends ServiceProvider
{
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
// You can add any Listener class here
// With handle() method inside of that class
],
];