Doing Best Practices in Laravel

A basic good practice would be to avoid repeating yourself. If you’re using a code snippet or a condition a number of times, it’d be better for you to prepare a method or a scope for that action. This way, you wouldn’t have to repeat yourself over and over. For example, let’s say we have an imaginary Controller as follows:

<?php

class UserController extends BaseController {

   //An imaginary method that lists all active users
   public function listUsers() {

      $users = User::where('active', 1)->get();

      return View::make('frontend.users.list')
         ->with('users', $users);
   }


   //An imaginary method that finds a specific user
   public function fetch($id) {

      $user = User::where('active', 1)->find($id);

       return View::make('frontend.users.single')
         ->with('user', $user);

   }

}

As you can see, the where() condition checks if active is repeated twice. In real-world examples, it would be used even more.

To prevent this, in Laravel, you can use query scopes. Query scopes are single functions that help you reuse the logic in Models. Let’s define a query scope in Model and change the Controller method as follows:

<?php

//Model File
Class User extends Eloquent {

   //We've defined a Query scope called active
   public function scopeActive($query) {
      return $query->where('active', 1);
   }

}




//Controller File
class UserController extends BaseController {

   //An imaginary method that lists all active users
   public function listUsers() {

      $users = User::active()->get();

      return View::make('frontend.users.list')
         ->with('users', $users);
   }


   //An imaginary method that finds a specific user
   public function fetch($id) {

      $user = User::active()->find($id);

      return View::make('frontend.users.single')
         ->with('user', $user);

   }

}

As you can see, we’ve defined a method called scopeActive() in Model, which is prefixed with the word scope and CamelCased. This way, Laravel can understand that it’s a query scope, and you can use that scope directly. As you can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().

Design patterns are advanced practices and can be used to keep the code tidy and systematic using various approaches.

 

Chapter 2 of 4

Comments

Pin It on Pinterest

Shares