Showing posts with label Laravel 5. Show all posts
Showing posts with label Laravel 5. Show all posts

Monday, 13 November 2017

Optimize images in your Laravel 5 application

This package is the Laravel 5.4 and up specific integration of spatie/image-optimizer. It can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools. The package will automatically detect which optimization binaries are installed on your system and use them.
Here's how you can use it:
use ImageOptimizer;

// the image will be replaced with an optimized version which should be smaller
ImageOptimizer::optimize($pathToImage);

// if you use a second parameter the package will not modify the original
ImageOptimizer::optimize($pathToImage, $pathToOptimizedImage);
You don't like facades you say? No problem! Just resolve a configured instance of Spatie\ImageOptimizer\OptimizerChain out of the container:
app(Spatie\ImageOptimizer\OptimizerChain::class)->optimize($pathToImage);
The package also contains a middleware to automatically optimize all images in an request.
Don't use Laravel you say? No problem! Just use the underlying spatie/image-optimizer directly.

Installation

You can install the package via composer:
composer require spatie/laravel-image-optimizer
The package will automatically register itself.
The package uses a bunch of binaries to optimize images. To learn which ones on how to install them, head over to the optimization tools section in the readme of the underlying image-optimizer package. That readme also contains info on what these tools will do to your images.
The package comes with some sane defaults to optimize images. You can modify that configuration by publishing the config file.
php artisan vendor:publish --provider="Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider"
This is the contents of the config/image-optimizer file that will be published:
use Spatie\ImageOptimizer\Optimizers\Svgo;
use Spatie\ImageOptimizer\Optimizers\Optipng;
use Spatie\ImageOptimizer\Optimizers\Gifsicle;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;

return [
    /**
     * When calling `optimize` the package will automatically determine which optimizers
     * should run for the given image.
     */
    'optimizers' => [

        Jpegoptim::class => [
            '--strip-all',  // this strips out all text information such as comments and EXIF data
            '--all-progressive'  // this will make sure the resulting image is a progressive one
        ],

        Pngquant::class => [
            '--force' // required parameter for this package
        ],

        Optipng::class => [
            '-i0', // this will result in a non-interlaced, progressive scanned image
            '-o2',  // this set the optimization level to two (multiple IDAT compression trials)
            '-quiet' // required parameter for this package
        ],

        Svgo::class => [
            '--disable=cleanupIDs' // disabling because it is know to cause troubles
        ],

        Gifsicle::class => [
            '-b', // required parameter for this package
            '-O3' // this produces the slowest but best results
        ],
    ],

    /**
     * The maximum time in seconds each optimizer is allowed to run separately.
     */
    'timeout' => 60,

    /**
     * If set to `true` all output of the optimizer binaries will be appended to the default log.
     * You can also set this to a class that implements `Psr\Log\LoggerInterface`.
     */
    'log_optimizer_activity' => false,
];
If you want to automatically optimize images that get uploaded to your application add the \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class in the http kernel.
// app/Http/Kernel.php
protected $routeMiddleware = [
   ...
   'optimizeImages' => \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class,
];

Usage

You can resolve a configured instance of Spatie\ImageOptimizer\OptimizerChain out of the container:
// the image will be replaced with an optimized version which should be smaller
app(Spatie\ImageOptimizer\OptimizerChain::class)->optimize($pathToImage);

// if you use a second parameter the package will not modify the original
app(Spatie\ImageOptimizer\OptimizerChain::class)->optimize($pathToImage, $pathToOptimizedImage);

Using the facade

use ImageOptimizer;

// the image will be replaced with an optimized version which should be smaller
ImageOptimizer::optimize($pathToImage);

// if you use a second parameter the package will not modify the original
ImageOptimizer::optimize($pathToImage, $pathToOptimizedImage);
You don't like facades you say? No problem! Just resolve a configured instance of Spatie\ImageOptimizer\OptimizerChain out of the container:
app(Spatie\ImageOptimizer\OptimizerChain::class)->optimize($pathToImage);

Using the middleware

All images that in requests to routes that use the optimizeImages-middleware will be optimized automatically.
Route::middleware('optimizeImages')->group(function () {
    // all images will be optimized automatically
    Route::post('upload-images', 'UploadController@index');
});

Adding your own optimizers

To learn how to create your own optimizer read the "Writing custom optimizers" section in the readme of the underlying spatie/image-optimizer package.
You can add the fully qualified classname of your optimizer as a key in the optimizers array in the config file.

Example conversions


Here are some example conversions that were made by the optimizer.

Source: https://github.com/spatie/laravel-image-optimizer

Wednesday, 8 November 2017

How to generate UUID in Laravel 5 ?

What is UUID?

Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for version 1, 3, 4 and 5 UUIDs are built-in.

Installation

In Laravel 5.5 laravel-uuid will install via the new package discovery feature so you only need to add the package to your composer.json file


composer require "webpatser/laravel-uuid:^3.0"
after installation, you should see

Discovered Package: webpatser/laravel-uuid

and you are ready to go 

Usage

To quickly generate a UUID just do
Uuid::generate()
This will generate a version 1 Uuid object with a random generated MAC address.
To echo out the generated UUID, cast it to a string
(string) Uuid::generate()
or
Uuid::generate()->string

Advanced Usage

UUID creation

Generate a version 1, time-based, UUID. You can set the optional node to the MAC address. If not supplied it will generate a random MAC address.
Uuid::generate(1,'00:11:22:33:44:55');
Generate a version 3, name-based using MD5 hashing, UUID
Uuid::generate(3,'test', Uuid::NS_DNS);
Generate a version 4, truly random, UUID
Uuid::generate(4);
Generate a version 5, name-based using SHA-1 hashing, UUID
Uuid::generate(5,'test', Uuid::NS_DNS);

Some magic features

To import a UUID
$uuid = Uuid::import('d3d29d70-1d25-11e3-8591-034165a3a613');
Extract the time for a time-based UUID (version 1)
$uuid = Uuid::generate(1);
dd($uuid->time);
Extract the version of an UUID
$uuid = Uuid::generate(4);
dd($uuid->version);


Thursday, 30 March 2017

Laravel 5.4 Sub domain routing method with in application

Today I am going to share with you how to define and use sub domain routes better way in Laravel 5 application.

We almost need to create sub-domain of our main domain. But if you are using core PHP or Codeigniter, then you have to create code for new sub-domain and it always take time to develop again and again. However, In Laravel framework 5, they provide group routing that way we can define sub domain routes in same application or project of laravel. We can simply manage sub-domain from our main project that way we don't require to create always new project and code etc. But we can simply manage by single laravel application. so that we can reduce the file size in our server.

In this post i am going give you very simple example of use sub-domain routing of laravel. you have to just follow few step to create simple example from scratch. You can simply create this example in your localhost too.

In this example, we will create one main domain with two sub domain, as listed bellow:

1) laravelpractice.com
2) admin.laravelpractice.com
3) user.laravelpractice.com
Here, as listed above three domain. This example for only local. So i created there three domain. we will simply manage it by single laravel application. So let's proceed.

Step 1 : Install Laravel Fresh Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Add Sub-Domain in ServiceProvider

In this step, we require to register our new two subdomain in RouteServiceProvider, that way we can create new file for each subdomin like we create two sub-domain "admin" and "user" then we create new file admin.php and user.php in routes directory for define routing.

So, let's open RouteServiceProvider.php and put bellow code:

app/Providers/RouteServiceProvider.phpph
namespace App\Providers;
    use Illuminate\Support\Facades\Route;

    use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
    class RouteServiceProvider extends ServiceProvider
    {
    /**
    * This namespace is applied to your controller routes.
    *
    * In addition, it is set as the URL generator's root namespace.
    *
    * @var string
    */
    protected $namespace = 'App\Http\Controllers';
    /**

    * Define your route model bindings, pattern filters, etc.
    *
    * @return void
    */
    public function boot()
    {
    parent::boot();
    }
    /**

    * Define the routes for the application.
    *
    * @return void
    */
    public function map()
    {
    $this->mapApiRoutes();
    $this->mapWebRoutes();
    $this->mapAdminRoutes();
    $this->mapUserRoutes();

    }
    /**

    * Define the "web" routes for the application.
    *
    * These routes all receive session state, CSRF protection, etc.
    *
    * @return void
    */
    protected function mapWebRoutes()
    {
    Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/web.php'));
    }
    /**

    * Define the "api" routes for the application.
    *
    * These routes are typically stateless.
    *
    * @return void
    */
    protected function mapApiRoutes()
    {
    Route::prefix('api')
    ->middleware('api')
    ->namespace($this->namespace)
    ->group(base_path('routes/api.php'));
    }
    /**

    * Define the "admin" routes for the application.
    *
    * These routes are typically stateless.
    *
    * @return void
    */
    protected function mapAdminRoutes()
    {
    Route::namespace($this->namespace)
    ->group(base_path('routes/admin.php'));
    }
    /**

    * Define the "user" routes for the application.
    *
    * These routes are typically stateless.
    *
    * @return void
    */
    protected function mapUserRoutes()
    {
    Route::namespace($this->namespace)
    ->group(base_path('routes/user.php'));
    }

    }

Step 3 : Add Sub-Domain Routes
In Last step, we need to add routes for our main domain and two sub-domain that way we can simply make example. So Here first you have to just add new route in your web.php file for main domain and other two as listed bellow:

1) Admin Routes : Here you have to create new file admin.php in routes folder. in that file you have declare routes for admin sub domain.
2) User Routes : Here you have to create new file user.php in routes folder. in that file you have declare routes for user sub domain.
So, let's proceed with routes define:

routes/web.php

Route::get('/', function () {
dd('Welcome to main domain.');
});

routes/admin.php

Route::get('/', function () {
dd('Welcome to admin subdomain.');
});

routes/user.php

Route::get('/', function () {
dd('Welcome to user subdomain.');
});

Now we are ready to run simple example with our sub-domain. So, in this tutorial i explained i created two subdomain as listed above. So for locally we have to create three domain using virtualhost like as bellow:

1) laravelpractice.com
2) admin.laravelpractice.com
3) user.laravelpractice.com

You have to simple run in your browser.

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in Laravel

  WampServer: Download this file:  http://curl.haxx.se/ca/cacert.pem Place this file in the  C:\wamp64\bin\php\php7.1.9  folder Open  php.in...

Popular Articles