Photo from unsplash
Thumbnail

Laravel Tips dan Trik

Written by Zulzario Zaeri on June 20, 2024

2 min read

--- Views


Introduction

Dalam dunia pengembangan web, Laravel telah menjadi pilihan utama sebagai framework PHP yang powerful dan efisien. Artikel kali ini, saya akan berbagi tips best practice dalam penggunaan Laravel, membantu memaksimalkan produktivitas dalam project Anda.

Routing

Basic Routing

// ❌
Route::get('/', function() {
  return view('home');
});
Route::get('/blog', function() {
  return view('blog');
});
Route::get('/about', function() {
  return view('about');
});
 
// ✅
Route::get('/', [PagesController::class, 'home'])->name('home');
Route::get('/blog', [PagesController::class, 'blog'])->name('blog');
Route::get('/about', [PagesController::class, 'about'])->name('about');

Routing dengan Model

// ❌
Route::get('/user/{user}', function ($user) {
    $user = User::where('id', $user)->first();
 
    return $user;
});
 
// ✅
Route::get('/user/{user}', function (User $user) {
    return $user;
});

Invoke Method

Jika hanya terdapat satu method di dalam ClassController, gunakan invoke method.

// ❌
Route::get('/', [HomeController::class, 'index']);
 
// ✅
// routes/web.php
Route::get('/', HomeController::class);
 
// App/Http/Controller/HomeController.php
class HomeController extends Controller
{
    public function __invoke(Request $request)
    {
        // ...
    }
}

Route Resource

Routing kita kacau, solusinya gunakan route resource

// ❌
Route::middleware('auth')->get('/user', [UserController::class, 'show']);
Route::middleware('auth')->get('/user/new', [UserController::class, 'create']);
Route::middleware('auth')->get('/user/{user}/edit', [UserController::class, 'edit']);
Route::middleware('auth')->post('/user', [UserController::class, 'store']);
Route::middleware('auth')->patch('/user/{user}/edit', [UserController::class, 'update']);
Route::middleware('auth')->delete('/user/{user}/delete', [UserController::class, 'destroy']);
 
// ✅
Route::resource('user', UserController::class)->middleware('auth');

Route Multiple Resource

Jika route rosource banyak, kita bisa mempersingkat lagi dengan menggunakan route multiple resources

// ❌
Route::resource('users', UserController::class)->middleware('auth');
Route::resource('tags', TagController::class)->middleware('auth');
Route::resource('posts', PostController::class)->middleware('auth');
Route::resource('categories', CategoryController::class)->middleware('auth');
 
// ✅
Route::resources([
    UserController::class,
    TagController::class,
    PostController::class,
    CategoryController::class,
]);