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.

Saturday, July 30, 2016

Laravel : How to get user's tweets in json

Hi

Today we will learn how to get a user's tweets in json format in laravel 5.

Add the below line of code in your composer.json file.

{
    "require": {
        "j7mbo/twitter-api-php": "dev-master"
    }
}

And then update your composer with composer update command in your terminal.

Then in any controller where you want to get tweets, use below function.

public function twitter(){
        
        $settings = array(
            'oauth_access_token' => 'Your oauth access token',
            'oauth_access_token_secret' => 'Your oauth access token secret',
            'consumer_key' => 'Your consumer key',
            'consumer_secret' => 'Your consumer secret'
        );
        $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
        $getfield = '';
        $requestMethod = 'GET';


                $twitter = new \TwitterAPIExchange($settings);
                $feeds = $twitter->setGetfield($getfield)
                    ->buildOauth($url, $requestMethod)
                    ->performRequest();

        return json_encode($feeds);
        

    }


Please click or goto url https://themepacific.com/how-to-generate-api-key-consumer-token-access-key-for-twitter-oauth/994/, to generate your settings.

In above script if we use $getfield = '?user_id={user_id}', it will give tweets of that particular user. If it is left blank then it will give tweets of that user whom oauth access token belongs to. If you want to explore more then please goto url https://dev.twitter.com/rest/reference/get/statuses/user_timeline.

Hope it will help someone.

Thanks

Friday, July 22, 2016

Service Container in laravel 5

Hi

Today, we learn service container in larave 5.2

The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.


<?php

namespace App\Jobs;

use App\User;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Bus\SelfHandling;

class PurchasePodcast implements SelfHandling
{
    /**
     * The mailer implementation.
     */
    protected $mailer;

    /**
     * Create a new instance.
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function __construct(Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    /**
     * Purchase a podcast.
     *
     * @return void
     */
    public function handle()
    {
        //
    }
}


In this example, the PurchasePodcast job needs to send e-mails when a podcast is purchased. So, we will inject a service that is able to send e-mails. Since the service is injected, we are able to easily swap it out with another implementation. We are also able to easily "mock", or create a dummy implementation of the mailer when testing our application.

Thanks.

Saturday, July 16, 2016

PHP Dependency Injection with Laravel 5

Hi
Today, we will learn dependency injection in laravel.
In laravel 5, We can inject services or classes. These dependency injection techniques are very useful when we generating a large scale projects. Class dependencies are injected into the class through the constructor or setter methods.
Dependency solutions through service container simplifies the dependency injection logic for our controller by configuring the container. This really becomes crystallise if one class depends on a service, that service depends on other services and those services could also depend on more services, the container will manage that dependency results.
Example of container App/Repositories/BookDbRepository
<?php namespace App\Repositories;
use App\Book;
class BookDbRepository {
    public function all(){
       return Book::all();
    }
    public function insertData($requestData){
        $book = new Book;
        $book->title= $requestData['title'];
        $book->description= $requestData['description'];
        $book->author= $requestData['author'];
        $book->save();
    }
    public function updateData($id, $requestData){
        $book = Book::find($id);
        $book->title = $requestData['title'];
        $book->description = $requestData['description'];
        $book->author = $requestData['author'];
        $book->save();
    }
    public function deleteData($id){
        Book::find($id)->delete();
    }
}
Into BookDbRepository we can see 4 methods are specifies show, insert, update and delete. Where container has all power to change the database. Unfortunately, controller will talk to BookDbRepository for every new query requests of application.
After early changes, Lets see what effects has been done in our controller BookController class.
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\BookDbRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
class BookController extends Controller {
    protected $repo;
    public function __construct(BookDbRepository $repo)
    {
        $this->repo = $repo;
    }
public function index()
{
$allBooks = $this->repo->all();
        return View('books.bookList', compact('allBooks'));
}
public function store(PublishBookRequest $requestData)
{
        $this->repo->insertData($requestData);
        return redirect()->route('book.index')->with('message', 'New record has been added!');
}
public function update($id, PublishBookRequest $requestData)
{
        $this->repo->updateData($id, $requestData);
        return redirect()->route('book.index')->with('message', 'Record has been updated!');
}

public function destroy($id)
    {
        $this->repo->deleteData($id);
        return redirect()->route('book.index')->with('message', 'Record deleted successfully!');
    }
}
Clearly we can see that in constructor of class BookController , we have injected the instance of BookDbRepository class.
Thanks

Friday, July 8, 2016

Laravel 5.2 and MySQL dates

Hi

Today we will learn, how to use MySQL dates with laravel 5.2.

Starting with MySQL 5.7, 0000-00-00 00:00:00 is no longer considered a valid date, since strict mode is enabled by default. All timestamp columns should receive a valid default value when we insert records into our database. We may use the useCurrent method in our migrations to default the timestamp columns to the current timestamps, or we may make the timestamps nullable to allow null values:

$table->timestamp('foo')->nullable();

$table->timestamp('foo')->useCurrent();

$table->nullableTimestamps();

Thanks