Saturday, August 27, 2016

Laravel : how to use query scopes

Hi

Today we will learn how and where to use query scopes.

Some times we are repeating a code snippet or a condition a number of times. Suppose we have to find a list of users who are active and a user  which is active. In controller generally we will write
 <?php  
 class UserController extends BaseController {  
   // finding list of users who are active.  
   public function listUsers() {  
    $users = User::where('active', 1)->get();     
   }  
   // finding a user detail which is active.  
   public function userDetail($id) {  
    $user = User::where('active', 1)->find($id);   
   }  
 }  
 ?>  

As we can see, the where() condition checks "if active is" repeated twice.

To prevent this, in Laravel, we can use query scopes. Query scopes are single functions that help us 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 {  
   // finding list of users who are active.  
   public function listUsers() {  
    $users = User::active()->get();  
   }  
   // finding a user detail which is active.  
   public function userDetail($id) {  
    $user = User::active()->find($id);  
   }  
 }  
 ?>  

As we 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 we can use that scope directly. As we can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().

Thanks

Friday, August 19, 2016

Laravel : Customizing the default Error Page

Hi everyone

Today we will learn how to customize the default error page in laravel

We all know the famous "Whoops, looks like something went wrong." page, now what if we can easily customize this to match our overall template. All we need to do is modify the default app/Exceptions/Handler.php file and override the convertExceptionToResponse method:

<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\Debug\ExceptionHandler as SymfonyDisplayer;

class Handler extends ExceptionHandler
{
    /**
     * Convert the given exception into a Response instance.
     *
     * @param \Exception $e
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function convertExceptionToResponse(Exception $e)
    {
        $debug = config('app.debug', false);

        if ($debug) {
            return (new SymfonyDisplayer($debug))->createResponse($e);
        }

        return response()->view('errors.default', ['exception' => $e], 500);
    }
}

Now we can easily customize errors.default view located under resources/view/errors folder to our application need.

We still include the original error page when using APP_DEBUG=true for development, but we can remove those line if we don't want it.

Monday, August 8, 2016

Laravel Log files by date

Hello everyone

Today we will discuss about laravel logging system.

Laravel logging mechanism is pretty simple – it writes all the errors to a file at /storage/logs/laravel.log. It’s convenient until the file gets bigger. And then we have a problem to find a bug from yesterday or some days ago. How can we solve this?

When we want to see log in laravel then we SSH to our server, go to /storage/logs folder and run ls -l command for the files list with information. And see this:

-rw-rw-r-- 1 forge forge 31580639 Jul  4 07:52 laravel.log

From above log files, it is very difficult to find log for a specific day. But it is very easy to change from single log file to daily basis log file. it’s only one setting in config/app.php file:

    /*
    |--------------------------------------------------------------------------
    | Logging Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log settings for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Settings: "single", "daily", "syslog", "errorlog"
    |
    */

    'log' => env('APP_LOG', 'single'),

As we can see, by default the value is single file, but we can change it to daily or others – either in the config file itself, or in environment file .env.

When we change the setting to daily, instead of one laravel.log – we will get separate file for each date – something like laravel-2016-08-07.log.