Monday, 13 November 2017

Creating Your Own Configuration in Laravel

Laravel configuration allows you to define per-environment configuration with the excellent vlucas/phpdotenv package.
If you are new to Laravel, you might not yet know how you can create your configuration files in your projects and a few other helpful things that will help you master configuration. As always, the official documentation provides great information, and there are a few things we’ll cover here that I think will help people new to the Laravel framework.

How Does Configuration Work?

At a high level, configuration files are located in the config/ folder of a Laravel project. The framework ships with various configuration files that make it easy for you to do things like pick which database driver you want to use and define external services.
For example, here is a partial view of the config/services.php config file:
return [
    // ...
    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

        // ...
Note the env() calls that you can use to change values per-environment with the .env file or on the host system directly.
When you define an environment configuration on your machine, it takes precedence over the .env file.
The env() helper also allows you to specify a default value when the environment variable is missing on the system or the .env file. For example, the default connection in config/database.php is mysql when the DB_CONNECTIONenvironment variable is not defined:
<?php

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    // ...
];
All environment values from the phpdotenv package come back as strings, but the env() helper in Laravel does extra work with environment variables. For example, the Laravel helper converts “false” the string to Boolean false, the keyword “empty” to an empty string, and “null” to a null value. You can check out the source of the Illuminate support helpers.php file for more details.

Accessing the Configuration Service

The most common ways to access configuration in Laravel is through the Configuration service or the config() helper.
Here’s how you use the config service:
$ php artisan tinker

>>> app('config')->get('services');
=> [
     "mailgun" => [
       "domain" => null,
       "secret" => null,
     ],
     "ses" => [
       "key" => null,
       "secret" => null,
       "region" => "us-east-1",
     ],
     "sparkpost" => [
       "secret" => null,
     ],
     "stripe" => [
       "model" => "App\User",
       "key" => null,
       "secret" => null,
     ],
   ]
The config() helper provides convenience, and you can still access the configuration repository service if you don’t pass any arguments:
$ php artisan tinker

>>> config()
=> Illuminate\Config\Repository {#37}

>>> config()->get('services')
...
>>> config('services')

Working with Configuration

Configuration is defined in PHP arrays, and you can access those array values with a dot notation. The first part of the configuration key matches the name of the file. For example, the following is the config/services.php file:
$ php artisan tinker

>>> config('services.mailgun');
=> [
     "domain" => "mg.example.com",
     "secret" => "secret",
   ]
>>> config('services.mailgun.domain');
=> mg.example.com
Just like the env() helper, the config helper allows you to specify a default value if the configuration key isn’t defined:
$ php artisan tinker

>>> config('my.invalid.key', 'mg.example.com');
=> mg.example.com
You can also change/set configuration at runtime by passing the configuration helper an array:
>>> config(['example' => 'Hello World']);
=> null
>>> config('example');
=> "Hello World"

>>> config([
... 'view.paths' =>
... array_merge(config('view.paths'), ['my/other/path/'])
... ]);

Creating Your Own Configuration

You can create your own configuration files by adding them to the config/ folder:
$ touch config/api.php
You would then access the configuration values by prefixing “api”:
>>> config('api.base_url');
This is just an example, for services like APIs just use the config/services.php file by adding new keys, for example, let’s say you are adding auth0 to services.php:
<?php

return [
    'auth0' => [
        'secret' => env('AUTH0_CLIENT_SECRET')
    ],
];

Optimizing Configuration

When you deploy your application to production, you should optimize your configuration by running the following command:
$ php artisan config:cache
There are a couple of important points to make about this command:
  1. This command is not intended for development environments
  2. Make sure you are not calling env() outside of configuration files
When you cache configuration, things like tests will use these cached values. For example, your database credentials will be cached and running tests with database interactions will drop your database tables.
When you cache your configuration, make sure your code is not calling the env()helper. You should be using config() wherever you need to access configuration. The correct way to provide configuration to your application is using configuration files in tandem with environment variables with sensible default values.
You can clear the configuration cache with the following artisan command:
$ php artisan config:clear

Setup Bootstrap Sass with Laravel Elixir

Laravel Elixir is a fantastic package that simplifies working with Gulp. For the unfamiliar Gulp is a JavaScript task runner that allows you to automate tasks. It can be used for compiling CSS, concating and minifying JavaScript, and much more.
Gulp was designed to be faster than previous build tools by utilizing node streams and has become one of the go to build systems. Laravel Elixir is a wrapper around Gulp making the setup a breeze.
In this tutorial let’s take a look at how to setup Bootstrap Sass with Elixir in a default Laravel 5.1 install.

Installing NPM Dependencies

Both Bootstrap and Elixir are node packages that are available via NPM, node package manager. If you open up the default package.json file you will see a list of dependencies:
"dependencies": {
    "laravel-elixir": "^3.0.0",
    "bootstrap-sass": "^3.0.0"
}
From terminal, run npm install and both these packages will be installed as well as any of their dependencies. If you are familiar with composer for PHP then it’s almost identical.
After the command finishes running, you can look in the node_modules folder and see a list of all the packages.

Bootstrap Sass

Implementing Bootstrap into your project is now simple. Open resources/assets/sass/app.scss and uncomment this line:
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
Save it and run gulp, then you have all the Bootstrap styles ready for you to use. That’s literally all that is required.

Customizing Bootstrap Styles

If you are not happy with the default Bootstrap design you can easily customize it by overriding its variables. As an example let’s change the default font to Lato from Google Fonts.
Open resources/assets/sass/app.scss again and we can import the font and adjust the variable. Here is the whole file with these changes:
@import url(https://fonts.googleapis.com/css?family=Lato);
$font-family-sans-serif: 'Lato', sans-serif;
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
How this works is first we import the Lato font from Google. Next, we override Bootstrap’s existing variable for font-family. This works because Bootstrap uses the Saas !default. Here is how they describe it:
You can assign to variables if they aren’t already assigned by adding the !default flag to the end of the value. This means that if the variable has already been assigned to, it won’t be re-assigned, but if it doesn’t have a value yet, it will be given one.
To find a list of all the variables you can customize open:

node_modules/bootstrap-sass/assets/stylesheets/bootstrap/_variables.scss

Including Bootstrap JavaScript with Browserify

For including the Bootstrap JavaScript we have a few options. We could use their CDN, download it manually, or use a system called Browserify.
Browserify lets you require(‘modules’) in the browser by bundling up all of your dependencies.
Because we already have Bootstrap installed through NPM we can utilize browserify and pull these into our app.js file. First, we do need to install jQuery and let’s do it through NPM by running the following command:
npm install jquery --save
Now, create the following file: resources/assets/js/app.js and add the following code:
window.$ = window.jQuery = require('jquery')
require('bootstrap-sass');

$( document ).ready(function() {
    console.log($.fn.tooltip.Constructor.VERSION);
});
Bootstrap expects jQuery to be global and with the first line we are including jQuery and assigning it to the window. The second line is requiring Bootstrap JavaScript. The last section is just a jQuery on ready and logging out the bootstrap tooltip version. This is used to just confirm it’s loading as we expect.
Now, lets modify the gulpfile.js in the project root:
elixir(function(mix) {
    mix.sass('app.scss')
        .browserify('app.js');
});
The simplicity of this shows just how great Elixir is. By just adding .browserify('app.js') everything is handled automatically. After saving run gulpagain and this will be compiled into public/js/app.js
If you include this in your layout and load the site in a browser you should see 3.3.5showing in the console.

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);


Laravel 5.5 group by doesn't work

In Laravel5.5  I  got following error when I used group by on single column.


My query was like as below example so you can see on database query I simple get all users and group by with name. So, let's simply see how it is:
DB Query:
$users = DB::table("users")
->groupBy("name")
->get();
dd($users);
But when i run above query using database query builder i got following error, as you can see:

SQLSTATE[42000]: Syntax error or access violation: 1055 'laravel_test.users.id' isn't in GROUP BY (SQL: select * from `users` group by `name`)

I was thinking what is the issue because without group by it was working, but at last i found it how to solve it So we have to simply "strict" mode make it true into false in database.php file. So let's do it as bellow:
config/database.php
...
'strict' => true,
To
'strict' => false,
....
After that i hope you found your solution.


Grayscale Image Generate In Laravel 5 with example

Sometimes, we may require to make grayscale image when user upload image. grayscale image looks better if you have an good layout website. in article we will learn how to create grayscale image using intervention package in laravel. intervention package provide a lots of things to do with image like resize, Grayscale, write on image etc. intervention package is also perfect to generate grayscale image.
So, let's follow few step to generate grayscale image and upload it to our server. You can make grayscale image as like bellow preview, i added one originally image and another grayscale image looks.
Original Image:

Grayscale Image:


Lets Start,
First install intervention/image for generate grayscale image. this package through we can generate grayscale image for our project. so first fire bellow command in your cmd or terminal:
composer require intervention/image
Now we need to add provider path and alias path in config/app.php file so open that file and add bellow code.
config/app.php
return [
$provides => [
'Intervention\Image\ImageServiceProvider'
],
$aliases => [
'Image' => 'Intervention\Image\Facades\Image'
]
]

app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Image;
class ImageController extends Controller{
public function grayscaleImagePost(Request $request){
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$img = Image::make($image->getRealPath());
$img->greyscale()->save($destinationPath.'/'.$input['imagename']);
/*
Write Your Insert data code
*/
return back()
->with('success','Image Upload successful')
->with('imageName',$input['imagename']);
}
}
Step 5: Blade and Create Upload directory
Ok, in this last step we will create grayscaleImage.blade.php file for photo upload form and manage error message and also success message. So first create grayscaleImage.blade.php file and put bellow code:
resources/views/grayscaleImage.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<h1>Grayscale Image Uploading Demo</h1>
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<div class="row">
<div class="col-md-4">
<strong>Grayscale Image:</strong>
<br/>
<img src="/images/{{ Session::get('imageName') }}" width="500px" />
</div>
</div>
@endif
{!! Form::open(array('route' => 'grayscaleImagePost','enctype' => 'multipart/form-data')) !!}
<div class="row">
<div class="col-md-4">
<strong>Add Title:</strong>
{!! Form::text('title', null,array('class' => 'form-control','placeholder'=>'Add Title')) !!}
</div>
<div class="col-md-12">
<strong>Add Image:</strong>
{!! Form::file('image', array('class' => 'image')) !!}
</div>
<div class="col-md-12">
<br/>
<button type="submit" class="btn btn-success">Upload Image</button>
</div>
</div>
{!! Form::close() !!}
</div>
@endsection
Ok, at last create directory in your public folder images and please give permission to that folder and check....

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