Thursday 30 March 2017

New feature in laravel 5.4 Route and Model Binding

In this article i will explain route model binding .

Route model binding provides a useful way to automatically method-inject a model's instance into your route closures, or controller actions. For example, if a user visits /users/1, thanks to route model binding, we can make Laravel automatically fetch the Users with an id of 1, and then inject that instance into your controller action.                            

routes/web.php

Route::get('users/{users}', 'UsersController@show');

app/Http/Controllers/UsersController.php

public function show($id)
    {
       $users = User::find($id);
       return $users;

    }



Instead of above code we can bind the model to function. Please find below code.


app/Http/Controllers/UsersController.php

public function show(User $users)
    {
       return $users;

    }

User is a model name and $users form route parameter.

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.

Tuesday 28 March 2017

Laravel 5.4 new features and changes

Here are the official changes and new features:

Two new Middleware

We have 2 new middleware: TrimStrings and ConvertEmptyStringsToNull.
  • Trim Strings middleware: automatically trim all the request data.
  • ConvertEmptyStringsToNull: automatically convert all strings to null.

Laravel Elixir will be renamed to Laravel Mix

The next version of Laravel Elixir will be built on Webpack, and it has a new name: Laravel Mix!

Meet the new Laravel Dusk

Laravel Dusk
Dusk is a new browser testing tool of Laravel. Now we can use Dusk to test everything, including Javascript applications (Ajax loading, jQuery, etc.). This is the most awaited feature of Laravel 5.4!

Use any class as Facade

We can use any class as a Facade in Laravel 5.4

Better Vue.js 2 support

Laravel 5.4 supports Vue 2 from the ground. if you love Vue, you're gonna love Vue 2 more!

Use Markdown in our emails

Loving Markdown? With Laravel 5.4, we can use Markdown in our emails. Awesome!

JSON based language files

We can be able to use JSON as our language files. This is great and very useful for multi-language projects.

Add components and slots to our Blade templates

We can add components and slots to our template in Laravel 5.4. Basically, this feature allows us to build reusable HTML elements for our app. If you're working with ReactJS, Angular 2 or Vue; you're right at home.

Minor route improvements

Route system will be enhanced. Route caching system is improved.
Now we can define a named route at the beginning:
Route::name('blog')->get('blog/{id}/', function ($id) {
});

Upgrade to Laravel 5.4

You can easily upgrade to Laravel 5.4 by following this guide:
https://laravel.com/docs/5.4/upgrade
Basically, you can just update your laravel/framework dependency to **5.4.* in your composer.json** file.
Find:
"laravel/framework": "5.3.*",
Change to:
"laravel/framework": "5.4.*",
And then run this command:
composer update
Please note that Elixir and some features have been changed. So if you still need some old features, don't upgrade yet.

Laravel 5.4's release notes

Learn more about all new features at:
https://laravel.com/docs/5.4/releases

Source Code

Laravel 5.4's source code is now available at:
https://github.com/laravel/framework

Final thoughts

Awesome! Let's start building your apps with Laravel 5.4!

Create, Edit, Update and Destroy functionality using Laravel 5.3

In this tutorial we will create basic CRUD functionality (Create, Edit, Update and Delete) using Laravel 5.3. There are a few changes done in the latest version of Laravel 5.3 that I found that broke my earlier code. Many tutorials that are available online are not up to date and were not much helpful so I decided to write a tutorial.

First of all we will have to create a resource route in your routes/web.php. This is one of the change in Laravel 5.3: In earlier versions there was just one routes.php file but in Laravel 5.3 the routes have been split into three files.

Note that I am adding this route to resource controller for an admin section.

------------------------------------------------------------------------------------
Route::group(['prefix' => 'admin'], function () {
  ...
  Route::resource('/categories', 'admin\CategoryController');
  ...
});

----------------------------------------------------------------

we have to install a package using composer to make HTML and FORM functionality work. Laravel 5.3 does not come with HTML and FORM package installed.

-------------------------------------------------------------------------
composer require "laravelcollective/html":"^5.2.0"
-------------------------------------------------------------------------

Next in the config/app.php we have to add the following providers and aliases at the end of each arrays like shown below:

------------------------------------------------------------
'providers'[

Collective\Html\HtmlServiceProvider::class,
],


'aliases' => [

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
'Input' => Illuminate\Support\Facades\Input::class,

],

------------------------------------------------------------

Next, We will have to create a controller using the following PHP artisan command in the command line editor. Make sure you are creating this inside your project directory.

------------------------------------------------------------

php artisan make:controller CategoryController --resource
------------------------------------------------------------

This command will create a Category resource controller with a few empty functions/methods such as index, create, edit, update, show and destroy. Note that these are REST functions.
The file will be created in Http/Controllers/CategoryController.php but we need this in the admin section so we will have to create a simple admin folder inside Controllers directory and move the CategoryController.php inside the admin/ folder.

In doing this we have changed its location so now we have to change the namespace as well. The namespace now changes from:



------------------------------------------------------------
namespace App\Http\Controllers;
To

namespace App\Http\Controllers\admin;


------------------------------------------------------------

Remember also to add the following entities and classes at the top of the file

------------------------------------------------------------
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Category;
use Validator;
use DB, Session, Crypt, Hash;
use Illuminate\Support\Facades\Input;
------------------------------------------------------------

Now, since this is an admin section I want to make sure that only the logged in user can access this page. To do this we will have to add authentication code inside our constructor in the CategoriesController.php page. You can also write a middleware to achieve this.

------------------------------------------------------------

public function __construct()
{
$this->middleware('auth');
}


------------------------------------------------------------


The Index() function

The below code needs to be added to the index function. The index function will handle listing of the categories along with the edit and delete buttons.

------------------------------------------------------------

public function index()
{
    // get all the categories
    $categories = DB::table('categories')->paginate(15);
    // load the view and pass the categories
    return view('admin.category.index', ['categories' => $categories]);
}

------------------------------------------------------------



We are simply querying the categories table and trying to paginate the results. The DB::table(‘categories’) part will fetch all the categories and the paginate function will paginate the results in 15 records each.

Next, We have to send the results to the view file. Usually view files goes inside resources/views/ directory but since this is an admin section we have to create a separate admin directory inside resources/views and add all the admin views inside it. So for CategoryController.php the views will be in resources/views/admin/category/ folder.
Lets have a closer look to the following line that we added in the controller.

------------------------------------------------------------

return view('admin.category.index', ['categories' => $categories]);
------------------------------------------------------------



We are going to send $categories array to admin/category/index.blade.php file. We use a dot notation to separate the directory.

This is what the index.blade.php looks like:

---------------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>All Categories</h1>
        <div><a href="{{ URL::to('admin/categories/create') }}">Create a Category</a></div>
        <!-- will be used to show any messages -->
        @if (Session::has('message'))
            <div class="alert alert-info">{{ Session::get('message') }}</div>
        @endif
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <td>ID</td>
                    <td>Category name</td>
                    <td>Actions</td>
                </tr>
            </thead>
            <tbody>
            @foreach($categories as $key => $value)
                <tr>
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->name }}</td>
                    <td>
                        <a class="btn btn-small btn-info" href="{{ URL::to('admin/categories/' . $value->id . '/edit') }}">Edit</a>
                        {{ Form::open(array('url' => 'admin/categories/' . $value->id, 'class' => 'btn btn-small')) }}
                            {{ Form::hidden('_method', 'DELETE') }}
                            {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
                        {{ Form::close() }}
                    </td>
                </tr>
            @endforeach
            {{ $categories->links() }}
            </tbody>
        </table>
    </div>
</div>
@endsection
---------------------------------------------------------------
We are extending the default Laravel layouts.app. To generate pagination links the following code needs to be added to the index.blade.php file.

-----------------------------------------------------------


{{ $categories->links() }}
-----------------------------------------------------------


The create() function

The create function will just display the view at resources/views/admin/category/create.blade.php



-----------------------------------------------------------
public function create()
{
    return view('admin.category.create');

}

-----------------------------------------------------------

And the create.blade.php file looks like:


-----------------------------------------------------------
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
         
        <h1>Create a Category</h1>
         
        <!-- show errors -->
        @if (count($errors) > 0)
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        {{ Form::open(array('url' => 'admin/categories')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Create Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The store() function

The store function will validate the input and store the data in the categories table.


-----------------------------------------------------------

public function store(Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'       => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = new Category;
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully created Category!');
        return redirect('admin/categories');
         
    }
}
-----------------------------------------------------------

The edit() function

The edit function displays the existing data in the input fields. It uses the layout resources/views/admin/category/edit.blade.php

-----------------------------------------------------------
public function edit($id)
{
    // get the category
    $category = Category::find($id);
    // show the edit form and pass the category
    return view('admin.category.edit')
    ->with('category', $category);

}

-----------------------------------------------------------
…and the edit.blade.php view looks like below:

-----------------------------------------------------------

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <h1>Edit {{ $category->name }}</h1>
        {{ Form::model($category, array('route' => array('categories.update', $category->id), 'method' => 'PUT')) }}
            <div class="form-group">
                {{ Form::label('name', 'Name') }}
                {{ Form::text('name', null, array('class' => 'form-control')) }}
            </div>
            {{ Form::submit('Edit the Category!', array('class' => 'btn btn-primary')) }}
        {{ Form::close() }}
    </div>
</div>
@endsection
-----------------------------------------------------------

The update() function

The update function will update the existing category.

-------------------------------------------------------------

public function update($id, Request $request)
{
    // validate
    // read more on validation at http://laravel.com/docs/validation
    $rules = array(
        'name'  => 'required',
    );
    $validator = Validator::make(Input::all(), $rules);
    $this->validate($request, [
        'name' => 'required'
    ]);
    if ($validator->fails()) {
        return redirect('admin/categories/create')
                    ->withErrors($validator)
                    ->withInput();
    } else {
        // store
        $category = Category::find($id);
        $category->name = Input::get('name');
        $category->visible = 1;
        $category->save();
        // redirect
        Session::flash('message', 'Successfully updated category!');
        return redirect('admin/categories');
         
    }

}
-------------------------------------------------------------

Finally the destroy() function

The destroy function deletes a category from the categories table.

-------------------------------------------------------------
public function destroy($id)
{
    // delete
    $category = Category::find($id);
    $category->delete();
    // redirect
    Session::flash('message', 'Successfully deleted the category!');
    return redirect('admin/categories')->with('status', 'Category Deleted!');
}
-------------------------------------------------------------

Difference between MySQL 5.6 and 5.7

Changes between MySQL 5.6 and 5.7

As usual with new MySQL versions, many new features have been added and some existing behaviors have been altered. This may cause potential issues with your setup if you neglect the importance of research and testing - new behavior may not be compatible with your application.
One of the main changes is the way that internal metrics are made available. In MySQL 5.6, you could query information_schema.global_status table and get some data about MySQL internals. In MySQL 5.7, this data is available through the performance_schema - such change may render your monitoring and trending software useless unless you enable ‘compatibility’ mode.
Some changes have been introduced in the default SQL mode - right now MySQL uses STRICT_TRANS_TABLES by default. This is great change but it sure can break compatibility with older applications.

Another important change is related to the authentication mechanism. Pre-4.1 passwords (‘old passwords’) have been removed, a new authentication system has been added. Amongst others, password expiration policy has been introduced - this can become a serious issue as the default settings may not be safe for systems upgraded from older MySQL versions - it’s better to set policies manually instead of relying on defaults, which may change in the future.

Those are definitely not the only changes which may pose a problem in an upgrade process. We’ve covered these in more detail in our database upgrade guide, “Migrating to MySQL 5.7”.

Sunday 26 March 2017

How to Import Large size .sql file using WAMP server

From this article i will explain how to upload large size (more then 1 GB) mysql file to our database.

Directly we can upload but we have a limit like max 128 MB.

So very easiest method is to upload large amount of data is cmd.
Open our wamp server mysql > mysql console .

then it will ask your mysql password .

Please enter your password then start your cmds.

1. mysql > use  database_name

It will show databse changed 

2. mysql> source file_path.

successfully uploaded your sql file database.




Thursday 23 March 2017

5.4 image validation only if image is uploaded

This article will show how to validate an image only if its uploaded  on Laravel 5.3 and 5.4. Here is a small web app where trying to upload images and perform some obligatory actions.

Example upload an users information with some details include profile pic.

routes\web.php


Auth::routes();


Taken basic authentication register form.

app\Http\Controllers\Auth\RegisterController.php

 protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
            'image' => 'sometimes|mimes:jpg,jpeg,bmp,png|max:10000',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        if($data['image']) {
            $file = $data['image'];
            //getting timestamp
            $timestamp =date('mdhis');
         
            $name = $timestamp. '-' .$file->getClientOriginalName();
       
            $file->move(public_path().'/images/', $name);
        }
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'image' => $name
             
        ]);
    }




 resources\views\auth\register.blade.php


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