Laravel – AppDividend https://appdividend.com Latest Code Tutorials Fri, 28 Jun 2019 17:37:37 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel – AppDividend https://appdividend.com 32 32 Laravel Collections Search Method Tutorial With Example https://appdividend.com/2019/04/08/laravel-collections-search-method-tutorial-with-example/ https://appdividend.com/2019/04/08/laravel-collections-search-method-tutorial-with-example/#respond Mon, 08 Apr 2019 17:39:36 +0000 http://localhost/wordpress/?p=5770 Laravel Collections Search Method Tutorial With Example

Laravel Collections Search Method Tutorial With Example is today’s topic. Laravel search method is used to search the collection for a given value. If the value is present in the collection, the key of the value is returned. If the value does not match any item, false is returned. If you are not familiar with Laravel Collections, […]

The post Laravel Collections Search Method Tutorial With Example appeared first on AppDividend.

]]>
Laravel Collections Search Method Tutorial With Example

Laravel Collections Search Method Tutorial With Example is today’s topic. Laravel search method is used to search the collection for a given value. If the value is present in the collection, the key of the value is returned. If the value does not match any item, false is returned. If you are not familiar with Laravel Collections, then check out my Laravel Collections Tutorial guide.

Laravel Collections Search Method

The search is done using the “loose” comparison, meaning the string with the integer value will be considered equal to the integer of the same value. To use “strict” comparison, we must pass true as the second argument to the method. You can find the collection search method inside Illuminate\Support\Collection class. See the method below.

public function search($value, $strict = false)
{
     if (! $this->useAsCallable($value)) {
         return array_search($value, $this->items, $strict);
     }

     foreach ($this->items as $key => $item) {
         if (call_user_func($value, $item, $key)) {
             return $key;
         }
     }

     return false;
}

Under the hood, the collection search() method calls array_search() method.

See the following example.

Write the following code inside the routes >> web.php file.

<?php

// web.php

Route::get('/', function () {
    $collection = collect([21, 19, 46, 29]);

    echo $collection->search(19)."\n";

});

Now, run the laravel project and you will see the following output 1. That means, 19 is there in the array, and its key is 1 which is returned.

Now, let’s search with a strict comparison. See the following code.

<?php

// app.php

Route::get('/', function () {
    $collection = collect([21, 19, 46, 29]);
    echo $collection->search('19', true);
});

The output will be false because we are searching 19 as a string and not an integer and we are checking in strict mode because we have passed the second parameter as a true.

Alternatively, you may pass in your callback to search for the first item that passes your truth test. It will return the first item’s index as an output. See the following code.

<?php

// app.php

Route::get('/', function () {
    $collection = collect([19, 21, 46, 29]);
    echo $collection->search(function($item, $key) {
        return $item > 19;
    });
});

In the above code, we are checking each collection item to be > 19. Now, 21 is the first element which is > 21, and its index is 1. So the output will be 1.

Finally, Laravel Collections Search Method Tutorial With Example is over.

The post Laravel Collections Search Method Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/08/laravel-collections-search-method-tutorial-with-example/feed/ 0
Laravel Collections Filter Method Tutorial With Example https://appdividend.com/2019/04/03/laravel-collections-filter-method-tutorial-with-example/ https://appdividend.com/2019/04/03/laravel-collections-filter-method-tutorial-with-example/#respond Wed, 03 Apr 2019 16:49:07 +0000 http://localhost/wordpress/?p=5664 Laravel Collections Filter Method Example

Laravel Collections Filter Method Tutorial With Example is today’s topic. If you are not familiar with Laravel Collections, then check out my Laravel Collections Tutorial guide. Laravel Eloquent uses Collections to return the results. Collections contain useful methods that make them very powerful and helpful to use. You can filter them, modify them and much […]

The post Laravel Collections Filter Method Tutorial With Example appeared first on AppDividend.

]]>
Laravel Collections Filter Method Example

Laravel Collections Filter Method Tutorial With Example is today’s topic. If you are not familiar with Laravel Collections, then check out my Laravel Collections Tutorial guide. Laravel Eloquent uses Collections to return the results. Collections contain useful methods that make them very powerful and helpful to use. You can filter them, modify them and much more with them very conveniently. The filter() method filters the collection using the given callback, keeping only those items that pass a given truth test.

Laravel Collections Filter Method

Laravel collection’s filter method calls array_filter() method on the underlying array, which, according to the PHP docs, preserves the array keys. This then results in your array being converted to a JavaScript object instead of an array.

You can find the collection filter method inside Illuminate\Support\Collection class. See the method below.

public function filter(callable $callback = null)
{
     if ($callback) {
         return new static(Arr::where($this->items, $callback));
     }

     return new static(array_filter($this->items));
}

The filter function takes a callback as an argument and run filter over each item. If the test fails for a particular item, then it will remove it from the collection.

Now, let’s see the example in action. For that, you need to install Laravel in your machine. I have already done it.

From now on, we will test each Laravel Collections Methods inside the routes >> web.php file.

Write the following code inside the web.php file.

<?php

// web.php

Route::get('/', function () {
    $collection = collect([19, 21, 29, 46]);

    $filtered = $collection->filter(function ($value, $key) {
        return $value > 21;
    });

    dd($filtered->all());
});

So, we have checked each collection item against 21 and if any item > 21 in the collection then it will be included in a new array.

Now, start the Laravel server by typing the following command in your project root.

php artisan serve

Go to the http://localhost:8000, and you will see the following output.

Laravel Collections Filter Method Tutorial With Example

 

That means it has created an array with all the items > 21. Rest items will be removed from the collection.

If no callback is supplied, all entries of the collection that are equivalent to false will be removed.

<?php

// web.php

Route::get('/', function () {
    $collection = collect([0, 1, 2, 3, 4, 5]);

    $filtered = $collection->filter();

    dd($filtered->all());
});

In the above code, entry will be removed because it has taken as a boolean 0 which is false. The output is following.

Laravel Collections Filter Method

Finally, Laravel Collections Filter Method Tutorial With Example is over.

The post Laravel Collections Filter Method Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/03/laravel-collections-filter-method-tutorial-with-example/feed/ 0
How To Create Multilingual Website using Laravel Localization https://appdividend.com/2019/04/01/how-to-create-multilingual-website-using-laravel-localization/ https://appdividend.com/2019/04/01/how-to-create-multilingual-website-using-laravel-localization/#comments Mon, 01 Apr 2019 17:50:37 +0000 http://localhost/wordpress/?p=5551 How To Create Multilingual Website using Laravel Localization

In this tutorial, we will see How To Create Multilingual Website using Laravel Localization. For this example, we will use Laravel 5.8, and we will do it from scratch. If you are not familiar with Laravel 5.8, then please check out my Laravel 5.8 CRUD Example. There are so many different ways, like using the […]

The post How To Create Multilingual Website using Laravel Localization appeared first on AppDividend.

]]>
How To Create Multilingual Website using Laravel Localization

In this tutorial, we will see How To Create Multilingual Website using Laravel Localization. For this example, we will use Laravel 5.8, and we will do it from scratch. If you are not familiar with Laravel 5.8, then please check out my Laravel 5.8 CRUD Example. There are so many different ways, like using the third party packages or build it from scratch using localization of Laravel. You can make the Middleware to handle a localization based on the user’s selected language, or you can use localization based on a specific route.

Create Multilingual Website using Laravel Localization

Laravel’s localization features provide a convenient way to retrieve strings in various languages, allowing us to support the multiple languages within your application quickly. Language strings are stored in the files within the resources/lang directory. Within that directory, there should be a subdirectory for each language supported by the application.

We will create the middleware to check if the locale is set then change the locale of the application. So let’s get started by installing a fresh copy of Laravel. Right now, Laravel’s 5.8 version is the latest version. Yours might be different from me depending on the future.

Step 1: Install Laravel 5.8

Type the following command in your terminal.

laravel new localization

or

composer create-project laravel/laravel localization

 

Laravel Localization

Go inside the project. For this project, we do not need to connect our application to the database because it is a frontend. So, I am not connecting this laravel app to the database. It is related to the frontend and not the database because we do not need for this example.

By default, our application’s local language is English or en.

You can find it on the config >> app.php file.

// app.php 

/*
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |--------------------------------------------------------------------------
    |
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    |
    */

    'locale' => 'en',

Here, the locale is set to en.

Now, if you check the resources >> lang folder, there is one folder called en, in which there are some files like auth.php, pagination.php, passwords.php, validation.php.

So, these files are translation files. Let’s check the auth.php file.

<?php

// auth.php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used during authentication for various
    | messages that we need to display to the user. You are free to modify
    | these language lines according to your application's requirements.
    |
    */

    'failed' => 'These credentials do not match our records.',
    'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',

];

So, this file returns an array which has key-value pair. So, here you can define any key you like, but the values are on your language specific statements.

An app.php file’s root folder name is en, so translation to these file’s statement is in English language or en, if the root folder is fr means french translation then the app.php file might look like below.

<?php

// auth.php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines are used during authentication for various
    | messages that we need to display to the user. You are free to modify
    | these language lines according to your application's requirements.
    |
    */

    'failed' => 'Ces informations d'identification ne correspondent pas à nos enregistrements',
    'throttle' => 'Trop de tentatives de connexion. Veuillez réessayer dans: secondes secondes.',

];

Remember, you need to add the same keys for all of your translation files across the different languages, change the values respective to your languages.

In the above code, we have written two items, which are failed and throttle and the values are translated into the French language.

So, when the user changes the languages, these statements will be displayed because in the view file, we will call it by its key and due to middleware it will map to the correct languages.

Step 2: Creating Translation Files

Okay, now we will go for three languages. English is already there.

  1. French
  2. Spanish
  3. Japanese

So, let’s create a folder inside the resources >> lang folder.

 

Website using Laravel Localization

Now, inside all of the four folders, create a file called sentence.php and add the following code.

For en >> sentence.php file,

<?php

// sentence.php

return [
  'welcome' => 'Welcome Friend'
];

For es >> sentence.php file,

<?php

// sentence.php

return [
  'welcome' => 'Bienvenido amigo'
];

For fr >> sentence.php file,

<?php

// sentence.php

return [
  'welcome' => 'Bienvenue mon ami'
];

And last, jp >> sentence.php file.

<?php

// sentence.php

return [
  'welcome' => 'ようこそ友達'
];

You can put as many texts as you want. I have just taken one text for this demo.

Now we have placed all translations in place, let’s start working on the views and make our application load above translations.

Step 3: Setup the view.

First, create layouts folder inside resources >> views folder and inside that layouts folder, create an app.blade.php file and add the following code.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                Language <span class="caret"></span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="lang/en"><img src="{{asset('img/us.png')}}" width="30px" height="20x"> English</a>
                                <a class="dropdown-item" href="lang/fr"><img src="{{asset('img/fr.png')}}" width="30px" height="20x"> French</a>
                                <a class="dropdown-item" href="lang/es"><img src="{{asset('img/es.png')}}" width="30px" height="20x"> Spanish</a>
                                <a class="dropdown-item" href="lang/jp"><img src="{{asset('img/jp.png')}}" width="30px" height="20x"> Japanese</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Now open your welcome.blade.php file, which is by default inside the resources >> views folder and place below code which includes a markup just for a languages dropdown.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    hello
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 4: Setup route, controller, and middleware

Now, inside routes >> web.php, add the following route.

Route::get('lang/{locale}', 'HomeController@lang');

Define a lang method inside the HomeController.php file. You can create a controller using the following command.

php artisan make:controller HomeController

Write the following code inside that file.

<?php

// HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App;

class HomeController extends Controller
{
    public function lang($locale)
    {
        App::setLocale($locale);
        session()->put('locale', $locale);
        return redirect()->back();
    }
}

So, this function will see the locale and put it into the session.

Now, create a middleware using the following command.

php artisan make:middleware Localization

It will create a file inside the app >> Http >> Middleware folder.

Now open your newly created middleware file called Localization.php and update the handle method with below code. So, our final file looks like below.

<?php

// Localization.php

namespace App\Http\Middleware;

use Closure;
use App;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

Step 5: Register the Localization Middleware

Now add the middleware in App\Http\Kernel‘s $middlewareGroup’s array like so.

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Localization::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

Now, one final thing is remaining. Add the following code inside the resources >> views >> layouts >> app.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        @php $locale = session()->get('locale'); @endphp
                        <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                Language <span class="caret"></span>
                            </a>
                            @switch($locale)
                                @case('fr')
                                <img src="{{asset('img/fr.png')}}" width="30px" height="20x"> French
                                @break
                                @case('es')
                                <img src="{{asset('img/jp.png')}}" width="30px" height="20x"> Spain
                                @break
                                @case('jp')
                                <img src="{{asset('img/jp.png')}}" width="30px" height="20x"> Japanese
                                @break
                                @default
                                <img src="{{asset('img/us.png')}}" width="30px" height="20x"> English
                            @endswitch
                            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="lang/en"><img src="{{asset('img/us.png')}}" width="30px" height="20x"> English</a>
                                <a class="dropdown-item" href="lang/fr"><img src="{{asset('img/fr.png')}}" width="30px" height="20x"> French</a>
                                <a class="dropdown-item" href="lang/es"><img src="{{asset('img/es.png')}}" width="30px" height="20x"> Spanish</a>
                                <a class="dropdown-item" href="lang/jp"><img src="{{asset('img/jp.png')}}" width="30px" height="20x"> Japanese</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

In the above code, if we change the language, dropdown still shows Language instead of the current locale. We can fix by adding a switch statement and check what locale we have and based on that we will show the current locale with a flag icon like below.

Finally, add the following code inside the resources >> views >> welcome.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                <p>{{ trans('sentence.welcome')}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Here, I have used the trans() function which will take one argument, and it is the filename.array_key_name.

Now, if you have done all correct till now, then go to the root route inside the browser, and you will see the drop-down with the four languages.

Select the language, and you will see the welcome message in a different language.

Finally, How To Create Multilingual Website using Laravel Localization Tutorial With Example is over.

The post How To Create Multilingual Website using Laravel Localization appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/01/how-to-create-multilingual-website-using-laravel-localization/feed/ 2
Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding https://appdividend.com/2019/03/11/laravel-model-factories-tutorial-with-example/ https://appdividend.com/2019/03/11/laravel-model-factories-tutorial-with-example/#comments Mon, 11 Mar 2019 18:39:26 +0000 http://localhost/wordpress/?p=5113 Laravel 5.8 Seeding

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding is today’s topic. Generating fake data manually for each model seed is cumbersome. Instead, you can use model factories to generate large amounts of database records conveniently. Laravel has feature called model factories that allows us to generate fake data. It is beneficial for testing […]

The post Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding appeared first on AppDividend.

]]>
Laravel 5.8 Seeding

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding is today’s topic. Generating fake data manually for each model seed is cumbersome. Instead, you can use model factories to generate large amounts of database records conveniently. Laravel has feature called model factories that allows us to generate fake data. It is beneficial for testing and seeding fake data into the database to see the code in action before any real-time user data comes in your application. Let’s deep dive into the Model Factories in Laravel.

Laravel Model Factories Tutorial

Faker is the PHP library that generates fake data for you. Whether you need to bootstrap your database, fill-in your persistence to stress test it or anonymize data taken from the production service, Faker is for you. You can find the faker documentation here.

By default, Laravel installs the faker library as a dependency. But you can also use the faker library to stand alone with any PHP project. You can install it using the following command. Remember, you do not need to install it with Laravel because by default it ships with Laravel.

composer require fzaninotto/faker

Okay, now back to the Laravel. Right now, Laravel 5.8 is the latest version. So install laravel.

composer create-project laravel/laravel blog --prefer-dist

Now, set the database credentials inside the .env file.

Next, create an Internet model and migration file by the following command.

php artisan make:model Internet -m

Switch to the create_internets_table.php file and add the following schema.

// create_internets_table.php

public function up()
{
    Schema::create('internets', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('safeEmail');
        $table->string('domainName');
        $table->string('url');
        $table->string('ipv6');
        $table->timestamps();
    });
}

Now, migrate using the following command.

php artisan migrate

Also, create an InternetFactory by using the following command.

php artisan make:factory InternetFactory

It will create an InternetFactory.php file inside the database >> factories >> InternetFactory.php file.

<?php

// InternetFactory.php

use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) {
    return [
        //
    ];
});

Right now, the above file is in the default state, but we need to add some attribute. Write the following code inside the InternetFactory.php file.

<?php

// InternetFactory.php

use Faker\Generator as Faker;
use App\Internet;

$factory->define(Internet::class, function (Faker $faker) {
    return [
        'safeEmail' => $faker->safeEmail,
        'domainName' => $faker->domainName,
        'url' => $faker->url,
        'ipv6' => $faker->ipv6
    ];
});

The $faker->safeEmail will create fake safeEmail.

The $faker->domainName will create a fake domain name.

The $faker->url will create a fake URL.

The $faker->ipv6 will create a fake IPV6 address.

These are some attributes provided by the faker library. So, it will help us to create a different type of fake data. You can find more on this url.

In the above code, we have defined a factory for Internet.php model and passing it as a first parameter. Then we have the callback function that defines the data and returns it in an array.

Laravel Database Seeding

Next step is to create a table seeder. So type the following command to generate a table seeder for internets table.

php artisan make:seeder InternetsTableSeeder

Now, inside that file, we will write the code that will generate the fake records inside the database.

The file will be created inside the database >> seeds >> InternetsTableSeeder.php file.

Write the following code inside that file.

<?php

// InternetsTableSeeder.php

use Illuminate\Database\Seeder;
use App\Internet;

class InternetsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $count = 100;
        factory(Internet::class, $count)->create();
    }
}

When the above file runs, it will create 100 fake records in the database.

Okay, now it’s time to run the Seeder file. So write the following code inside the DatabaseSeeder.php file which is inside the database >> seeds folder.

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(InternetsTableSeeder::class);
    }
}

Once you have written your seeder class, you may need to regenerate the Composer’s autoloader using the dump-autoload command.

composer dump-autoload

Then type the following command.

php artisan db:seed

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Fake Data

It has generated 100 fake records inside the internets table. See the following image.

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding

We have generated fake records using the faker library using Model Factory.

Testing Model Factories

Let’s create a new test by hitting the following command.

php artisan make:test InternetsTest

It will create a file called InternetsTest.php inside the tests >> Feature folder.

Write the testInternetsCreation() function inside the InternetsTest.php file.

<?php

// InternetsTest.php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class InternetsTest extends TestCase
{
    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function testInternetsCreation()
    {
        $safeEmail = 'lyric.heidenreich@example.org';
        $domainName = 'rice.com';
        $url = 'http://wintheiser.net/est-unde-nam-vel-non-eos-porro-sunt-rerum';
        $ipv6 = '2626:5d6c:6597:1361:7106:5baa:def4:4270';

        $this->assertDatabaseHas('internets', [
            'safeEmail' => $safeEmail,
            'domainName' => $domainName,
            'url' => $url,
            'ipv6' => $ipv6,
        ]);
    }
}

Laravel provides the variety of helpful tools to make it easier to test your database driven applications. First, you may use the assetDatabaseHas helper to assert that data exists in the database matching a given set of criteria. The assetDatabaseHas method and other helpers like it are for convenience. You are free to use any of PHPUnit’s built-in assertion methods to supplement your tests.

Now, we need to run the test. So go to the terminal and type the following command. Remember, your terminal is open inside the project root.

vendor/bin/phpunit tests/Feature/InternetsTest.php

See the output below.

 

Testing Model Factories

Finally, Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding is over.

The post Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/11/laravel-model-factories-tutorial-with-example/feed/ 2
Laravel Eloquent Collection Tutorial With Example | Laravel 5.8 Guide https://appdividend.com/2019/03/10/laravel-eloquent-collection-tutorial-with-example/ https://appdividend.com/2019/03/10/laravel-eloquent-collection-tutorial-with-example/#comments Sun, 10 Mar 2019 18:27:52 +0000 http://localhost/wordpress/?p=5076 Laravel Eloquent Collection Tutorial Example

Laravel Eloquent Collection Tutorial With Example is today’s topic. The Eloquent collection object extends the Laravel base collection, so it naturally inherits the dozens of methods used to work with an underlying array of Eloquent models fluently. All multi-result sets returned by Eloquent are instances of an Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or […]

The post Laravel Eloquent Collection Tutorial With Example | Laravel 5.8 Guide appeared first on AppDividend.

]]>
Laravel Eloquent Collection Tutorial Example

Laravel Eloquent Collection Tutorial With Example is today’s topic. The Eloquent collection object extends the Laravel base collection, so it naturally inherits the dozens of methods used to work with an underlying array of Eloquent models fluently. All multi-result sets returned by Eloquent are instances of an Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.

Laravel Eloquent Collection Tutorial

We will start this tutorial by installing fresh Laravel. Right now, Laravel 5.8 is the latest version of Laravel. If you are new to Laravel 5.8, then check out my Laravel 5.8 CRUD tutorial for starters. Install Laravel using the following command.

composer create-project --prefer-dist laravel/laravel blog

Okay, now set up the database inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=root

Next step is to migrate the tables inside the database using the following command.

php artisan migrate

Seed Database

Laravel includes the simple method of seeding your database with test data using seed classes. All the seed classes are stored in the database/seeds directory. Seed classes may have any name you want but probably it should follow some sensible convention, such as UsersTableSeeder, etc. By default, the DatabaseSeeder class is defined for you. From this class, you can use the call() method to run other seed classes, allowing you to control the seeding order.

Create a UsersTableSeeder.php file using the following command.

php artisan make:seeder UsersTableSeeder

We will use Model factories to generate fake data.

Now, write the following code inside the UsersTableSeeder.php file.

<?php

// UsersTableSeeder.php

use Illuminate\Database\Seeder;
use Illuminate\Support\Str;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();
        for($i=0;$i<50;$i++) {
            \App\User::create([
                'name' => $faker->name,
                'email' => $faker->unique()->safeEmail,
                'email_verified_at' => now(),
                'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
                'remember_token' => Str::random(10),
            ]);
        }
    }
}

So, it will generate 50 random users records in the database.

Now, we need to modify the DatabaseSeeder.php file.

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
    }
}

Before you seed the file, we need to regenerate the Composer’s autoloader using the dump-autoload command.

composer dump-autoload

Okay, now go to the terminal and run the seed file using the following command.

php artisan db:seed

It will generate fake data in the users table.

Laravel Eloquent Collection Tutorial

 

So now, we have test data to work with, and we can query the database using Laravel Eloquent Collection.

Query Data using Laravel Eloquent Collection

Now, write the following code inside the routes >> web.php file.

<?php

// web.php

Route::get('/', function () {
    $users = \App\User::all();
    foreach ($users as $user) {
        echo '<pre>';
        echo $user->name;
        echo '</pre>';
    }
});

In the above code, we are displaying only the name of the users in preformatted HTML view.

If you go to the root route, then you will see something like below image. Of course, the data will be different because the faker library randomly generates it. It will be 50 names.

 

Laravel 5.8 Guide

All collections also serve as the iterators, allowing us to loop over them as if they were simple PHP arrays.

The collections are much more potent than arrays and expose the variety of map / reduce operations that may be chained using the intuitive interface.

Laravel chunk() Collection Method

The chunk() method breaks a collection into multiple, smaller collections of the given size.

Write the following code inside the web.php file.

<?php

// web.php

Route::get('/', function () {
    $users = \App\User::all();
    $chunks = $users->chunk(2);
    $data = $chunks->toArray();
    echo '<pre>';
    print_r($data);
    echo '</pre>';
});

The output of the above code is following.

 

Laravel chunk() Collection Method

The chunk() method is especially useful in views when working with the grid system such as Bootstrap.

Laravel Custom Collections

If you need to use the custom Collection object with your extension methods, you may override the newCollection method on your model. See the following example of the User.php model.

<?php

// User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\CustomCollection;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}

Once you have defined the newCollection method, you will receive an instance of your custom collection anytime Eloquent returns the collection instance of that model. If you would like to use the custom collection for every model in your application, you should override a newCollection method on the base model class that is extended by all of your models. In the above example, we have override inside the User.php model class.

Okay, now create a CustomCollection.php file inside the app folder.

<?php

// CustomCollection.php

namespace App;

use Illuminate\Support\Collection;

class CustomCollection extends Collection 
{
    public function gotAllUsers()
    {
	dd($this->items);
    }
}

Here, $this->items have all the users records. We can access these records inside the CustomCollection class.

Finally, write the following code inside the web.php file.

<?php

// web.php

Route::get('/', function () {
    $users = \App\User::get();
    $users->gotAllUsers();
});

Refresh the root route, and the output is following. It is up to 50 records.

 

Laravel Custom Collections

Finally, Laravel Eloquent Collection Tutorial With Example is over.

The post Laravel Eloquent Collection Tutorial With Example | Laravel 5.8 Guide appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/10/laravel-eloquent-collection-tutorial-with-example/feed/ 1
Laravel Collections Tutorial With Example | Laravel 5.8 Guide https://appdividend.com/2019/03/10/laravel-collections-tutorial-with-example-laravel-5-8-guide/ https://appdividend.com/2019/03/10/laravel-collections-tutorial-with-example-laravel-5-8-guide/#respond Sun, 10 Mar 2019 16:30:05 +0000 http://localhost/wordpress/?p=5062 Laravel Collections Tutorial With Example

Laravel Collections Tutorial With Example is today’s topic. The Illuminate\Support\Collection class provides a convenient wrapper for working with PHP arrays of data. Laravel Collection class allows us to chain its methods to perform fluent mapping and reducing of the underlying array. In general, Laravel collections are immutable, meaning every Collection method returns an entirely new Collection instance. PHP […]

The post Laravel Collections Tutorial With Example | Laravel 5.8 Guide appeared first on AppDividend.

]]>
Laravel Collections Tutorial With Example

Laravel Collections Tutorial With Example is today’s topic. The Illuminate\Support\Collection class provides a convenient wrapper for working with PHP arrays of data. Laravel Collection class allows us to chain its methods to perform fluent mapping and reducing of the underlying array. In general, Laravel collections are immutable, meaning every Collection method returns an entirely new Collection instance.

Laravel Collections Tutorial

Laravel collections are an API wrapper for PHP array functions. But it has much more features than PHP array processing. We can also create a collection from an array.

Creating Collections in Laravel

The collect helper returns the new Illuminate\Support\Collection instance for the given array.

See the following simple example. If you have installed fresh laravel, then write the following code inside the routes >> web.php file.

<?php

// web.php

Route::get('/', function () {
    $arr = [19, 21, 46];
    $collection = collect($arr);
    dd($collection);
});

Now, start the Laravel development server using the following command.

php artisan serve

Go to this URL: http://localhost:8000 and see the output.

 

Laravel Collections Tutorial With Example | Laravel 5.8 Guide

So, we have successfully created collections from the PHP array.

Extending Collections

Collections are macroable, which means that it allows us to add additional methods to the Collection class at run time.

Let’s see the following example. So write the following code inside the routes >> web.php file.

<?php

// web.php

use Illuminate\Support\Collection;
use Illuminate\Support\Str;

Route::get('/', function () {
    Collection::macro('ucFirst', function () {
        return $this->map(function ($value) {
            return Str::ucfirst($value);
        });
    });
    $collection = collect(['krunal', 'lathiya']);
    $result = $collection->ucFirst();
    dd($result);
});

So, here first, we have imported two namespaces for Collection and Str. Then we have used the macro method of Collection class and map every element of the collection and convert into ucfirst convention means the string’s first character will be converted to Capital Letter.

See the output below.

 

Extending Collections in Laravel

trait Macroable

In the above example, we have used the Macroable trait which has the following syntax.

static macro(string $name, object|callable $macro)

So, the first argument is a string and the second argument is callable macro or object, in our case, it is a collection of items which then iterate through the map function.

You can find more about Collection on this link.

Laravel Collection Methods

There are so many methods available for collections in Laravel. You can find it here. We will see one or two methods in this tutorial.

Laravel avg() method

The avg method returns an average value of the given key if the key is provided otherwise gives an avg of the values. See the following example.

<?php

// web.php

Route::get('/', function () {
    $result = collect([19, 21, 18, 46])->avg();
    dd($result);
});

We will get 26 as an output.

Laravel count() method

The count() method returns a total number of items in the collection.

<?php

// web.php

Route::get('/', function () {
    $result = collect([19, 21, 18, 46])->count();
    dd($result);
});

Go to the browser and refresh the root route and you will see the in the output.

There are so many methods available for collections in Laravel. Laravel collections are one of the most powerful provisions. They are what PHP arrays should be, but better.

Finally, Laravel Collections Tutorial With Example | Laravel 5.8 Guide is over. Thanks for taking.

The post Laravel Collections Tutorial With Example | Laravel 5.8 Guide appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/10/laravel-collections-tutorial-with-example-laravel-5-8-guide/feed/ 0
Laravel 5.8 Form Validation Tutorial With Example https://appdividend.com/2019/03/09/laravel-5-8-form-validation-tutorial-with-example/ https://appdividend.com/2019/03/09/laravel-5-8-form-validation-tutorial-with-example/#comments Sat, 09 Mar 2019 15:20:44 +0000 http://localhost/wordpress/?p=5023 Laravel 5.8 Validation Tutorial

Laravel 5.8 Form Validation Tutorial With Example is today’s topic. Laravel  Framework provides many different approaches to validate your application’s form data. By default, Laravel’s base controller class uses the ValidateRequests trait which provides the convenient method to validate incoming HTTP request with a variety of powerful validation rules. We can use the Validation differently […]

The post Laravel 5.8 Form Validation Tutorial With Example appeared first on AppDividend.

]]>
Laravel 5.8 Validation Tutorial

Laravel 5.8 Form Validation Tutorial With Example is today’s topic. Laravel  Framework provides many different approaches to validate your application’s form data. By default, Laravel’s base controller class uses the ValidateRequests trait which provides the convenient method to validate incoming HTTP request with a variety of powerful validation rules. We can use the Validation differently in Laravel. We can either use inside the controller’s method or create a FormRequest class to validate the incoming requests. In this tutorial, we will all ways to validate Laravel.

Laravel 5.8 Form Validation Tutorial

Okay, now the first step is to install Laravel 5.8. If you are new to Laravel 5.8, then check out my Laravel 5.8 CRUD tutorial on this blog. So, install the Laravel 5.8 using the following command. Right now, Laravel 5.8 is the latest version. So in the future, you may need to specify the version while installing the Laravel 5.8.

composer create-project --prefer-dist laravel/laravel blog

Okay, now go inside the project folder and open the project in the code editor.

Now, create a MySQL database and also connect that database to Laravel 5.8. Write the database credentials inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=root

Create a FormController.php file using the following command.

php artisan make:controller FormController

Create two methods inside the FormController.php file.

<?php

// FormController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function create()
    {

    }

    public function store(Request $request)
    {
        
    }
}

Now, write the two routes inside the routes >> web.php file.

// web.php

Route::get('form', 'FormController@create')->name('form.create');
Route::post('form', 'FormController@store')->name('form.store');

Now, create a model and migration file using the following command.

php artisan make:model Form -m

Write the following code inside the [timestamp]_create_forms_table.php file.

// create_forms_table.php

public function up()
{
        Schema::create('forms', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('item_name');
            $table->string('sku_no');
            $table->integer('price');
            $table->timestamps();
        });
}

Now, create a table using the following command.

php artisan migrate

Also, to prevent mass assignment exception, add the $fillable property.

<?php

// Form.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    protected $fillable = ['item_name', 'sku_no', 'price'];
}

Inside the views folder, create layout.blade.php file and add the following code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel 5.8 Form Validation Example Tutorial</title>
  <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="container">
    @yield('content')
  </div>
  <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>

Now, in the same folder, create one file called create.blade.php and add the following code.

<!-- create.blade.php -->

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Item
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('form.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Item Name:</label>
              <input type="text" class="form-control" name="item_name"/>
          </div>
          <div class="form-group">
              <label for="price">SKU Number :</label>
              <input type="text" class="form-control" name="sku_no"/>
          </div>
          <div class="form-group">
              <label for="quantity">Item Price :</label>
              <input type="text" class="form-control" name="price"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Item</button>
      </form>
  </div>
</div>
@endsection

Now, write the FormController’s create() function.

// FormController.php

public function create()
{
    return view('create');
}

Now, you can access the form on this URL: http://localhost:8000/form.

 

Laravel 5.8 Form Validation Tutorial With Example

Writing The Validation Logic

Okay, now we can write the validation logic inside FormController’s store() function.

// FormController.php

public function store(Request $request)
{
        $validatedData = $request->validate([
            'item_name' => 'required|max:255',
            'sku_no' => 'required|alpha_num',
            'price' => 'required|numeric',
        ]);
        \App\Form::create($validatedData);

        return response()->json('Form is successfully validated and data has been saved');
}

As you can see, we have passed the desired validation rules into the validate() method. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally and save the data in the database, and we get the json response.

If we submit the form without filling any values, then we get the error response like the following.

 

Laravel 5.8 Form Validation Tutorial With Example | Custom Validation

Stopping On First Validation Failure

Sometimes you may have requirement to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute.

// FormController.php

$validatedData = $request->validate([
      'item_name' => 'bail|required|max:255',
      'sku_no' => 'required|alpha_num',
      'price' => 'required|numeric',
 ]);

In this example, if the max rule on the item_name attribute fails, the max rule won’t checked. Rules will be validated in the order they are assigned.

Displaying Validation Errors

Laravel will automatically redirect the user back to their previous location. Also, all of the validation errors will automatically be flashed to a session.

Notice that we did not have to explicitly bind the error messages to a view in our GET route. It is because Laravel will check for the errors in the session data, and automatically bind them to the view if they are available.

In our example, we have iterated the $errors array variable inside the create.blade.php file. That is why we user can see the errors.

@if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
@endif

Form Request Validation in Laravel 5.8

In the above example, we have written the validation rules inside the controller function. We can also create a separate file to write the validation rules. For more complex validation scenarios, you may wish to create a “form request.” Form requests are the custom request classes that contain validation logic. To create a form request class, use the make: request Artisan CLI command.

php artisan make:request FieldRequest

It will create a file inside the app >> Http >> Requests folder called FieldRequest.php file.

Let’s add a few validation rules inside the rules method.

// FieldRequest.php

public function rules()
{
    return [
         'item_name' => 'bail|required|max:255',
         'sku_no' => 'required|alpha_num',
         'price' => 'required|numeric',
    ];
}

Also, you need to return true from the authorize() method inside the FieldRequest.php file. If you plan to have an authorization logic in another part of your application, return true from the authorize() method.

// FieldRequest.php

public function authorize()
{
        return true;
}

So, now, you do not need to re-write these rules inside the FormController.php’s store() function.

You need to import the FieldRequest namespace inside the FormController.php file and pass the FormRequest as a dependency injection to the store function.

<?php

// FormController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\FieldRequest;

class FormController extends Controller
{
    public function create()
    {
        return view('create');
    }

    public function store(FieldRequest $request)
    {
        $validatedData = $request->validated();
        \App\Form::create($validatedData);

        return response()->json('Form is successfully validated and data has been saved');
    }
}

If the validation fails, the redirect response will be generated to send a user back to their previous location. The errors will also be flashed to a session, so they are available for display.

Customizing The Error Messages

You may customize the error messages used by the form request by overriding the messages method. This method should return an array of attribute/rule pairs and their corresponding error messages.

// FieldRequest.php 

  /**
   * Get the error messages for the defined validation rules.
   *
   * @return array
   */
    public function messages()
    {
        return [
            'item_name.required' => 'An Item Name is required',
            'sku_no.required'  => 'An SKU NO is required',
            'price.required'  => 'The price is required',
        ];
    }

Save the file and again submit the form without any values and you will see these error messages instead of default error messages.

 

Customizing The Error Messages in Laravel

Manually Creating Validators

If you do not want to use a validate() method on the request, you may create the validator instance manually using the Validator facade. The make method on the facade generates a new validator instance.

// FormController.php

use Validator;

public function store(Request $request)
{
    $validatedData = Validator::make($request->all(), [
        'item_name' => 'bail|required|max:255',
        'sku_no' => 'required|alpha_num',
        'price' => 'required|numeric',
    ])->validate();

     \App\Form::create($validatedData);

     return response()->json('Form is successfully validated and data has been saved');
}

It will also give us the same output. If you would like to create the validator instance manually but still take advantage of the automatic redirection offered by the requests to validate() method, you may call the validate() method on an existing validator instance.

For more validation, you can check out Laravel 5.8’s official documentation.

Finally, Laravel 5.8 Form Validation Tutorial With Example is over.

The post Laravel 5.8 Form Validation Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/09/laravel-5-8-form-validation-tutorial-with-example/feed/ 5
Laravel 5.8 CRUD Tutorial With Example For Beginners https://appdividend.com/2019/03/08/laravel-5-8-crud-tutorial-with-example-for-beginners/ https://appdividend.com/2019/03/08/laravel-5-8-crud-tutorial-with-example-for-beginners/#comments Fri, 08 Mar 2019 12:16:20 +0000 http://localhost/wordpress/?p=4972 laravel 5.8 crud tutorial example

Laravel 5.8 CRUD Tutorial With Example For Beginners is today’s topic. You can upgrade your Laravel’s 5.8 version by going to this link. Laravel 5.8 continues the improvements made in Laravel 5.7 by introducing the following features. has-one-through Eloquent relationships. Improved email validation. convention-based automatic registration of authorization policies. DynamoDB cache and session drivers. Improved […]

The post Laravel 5.8 CRUD Tutorial With Example For Beginners appeared first on AppDividend.

]]>
laravel 5.8 crud tutorial example

Laravel 5.8 CRUD Tutorial With Example For Beginners is today’s topic. You can upgrade your Laravel’s 5.8 version by going to this link. Laravel 5.8 continues the improvements made in Laravel 5.7 by introducing the following features.

  1. has-one-through Eloquent relationships.
  2. Improved email validation.
  3. convention-based automatic registration of authorization policies.
  4. DynamoDB cache and session drivers.
  5. Improved scheduler timezone configuration.
  6. Support for assigning multiple authentication guards to broadcast channels.
  7. PSR-16 cache driver compliance, improvements to the artisan serve command.
  8. PHPUnit 8.0 support.
  9. Carbon 2.0 support.
  10. Pheanstalk 4.0 support, and a variety of other bug fixes and usability improvements.

You can find the detailed guide on Laravel 5.8 releases.

#Server Requirements For Laravel 5.8

The following are the server requirements.

  1. PHP >= 7.1.3
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
  6. XML PHP Extension
  7. Ctype PHP Extension
  8. JSON PHP Extension
  9. BCMath PHP Extension

#Prerequisites

For this project, I am using Visual Studio Code. If you do not know how to configure PHP on VSCode then I have also written the tutorial on this blog regarding how to configure Visual Studio Code For PHP Developers.

First, you need to check the PHP version. Type the following command.

php -v

My PHP version is 7.2.14.

Prerequisites of Laravel 5.8 CRUD

If your version is less than above PHP version, then I would suggest you upgrade your PHP version.

If you are on a Mac, then you can update your PHP version using homebrew.

First, remove the old versions of PHP and then install it using the following command.

brew install httpd php72
brew install php72 --with-httpd --with-thread-safety

For more information, check out this great guide.

Next thing is we need a Composer. The composer is a PHP Dependency Manager. We can pull the different packages using the composer.

Install the composer using the following command.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

Next step is to move the composer to the global directory.

mv composer.phar /usr/local/bin/composer

Now, your composer has been installed successfully.

#For Linux Ubuntu Guide

On Ubuntu, you can follow these instructions to install the latest PHP version as well as Composer.

First, add the ondrej/php PPA which contains the latest version of PHP.

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Next, install PHP 7.2 using the following command.

sudo apt-get install php7.2

Now, you need to install the required modules of PHP 7.2.

And Finally, install the Composer. Go to the home directory, and we will install composer using cURL.

curl -sS https://getcomposer.org/installer -o composer-setup.php

You can then install composer globally on your system by using the following command.

sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer

Now, type the following command in your terminal.

composer

It will display something like below.

Laravel 5.8 CRUD Tutorial

Laravel 5.8 CRUD Tutorial With Example

I have already written Laravel 5.6 CRUD, Laravel 5.7 CRUD on this blog.

You can install Laravel 5.8 via global installer or using the Composer Create-Project command.

composer create-project --prefer-dist laravel/laravel laravel58crud

 

Laravel 5.8 CRUD Tutorial With Example For Beginners

Now, go inside the project and open the project in your favorite editor.

cd laravel58crud
code .

#Step 1: Configure the MySQL Database

Now, first, in MySQL, you need to create the database, and then we need to connect that database to the Laravel application. You can also use phpmyadmin to create the database.

I have created a MySQL database called laravel58crud and now write the MySQL credentials inside the .env file. Before creating migrations, We will need to set up our database, assuming you know how to create a database using phpmyadmin. After creating the database, we will add the database credentials in our application. Laravel has a .env environment file which will have all the sensitive data like database details, mail driver details, etc. because it’s not recommended to store such information directly inside the code (environment files are not limited to PHP. They are used in all other significant frameworks). Values inside the .env files are loaded inside the files from the config directory. .env file is located at the root of our application.

Whenever you make changes to .env file then don’t forget to restart the server ( if you are using laravel dev server) and if you are using a virtual host and changes don’t seem to take effect then just run php artisan config:clear (This command will clear the configuration cache) in your terminal.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel58crud
DB_USERNAME=root
DB_PASSWORD=root

So now you will be able to connect the MySQL database.

Laravel always ships with migration files, so you can able to generate the tables in the database using the following command.

php artisan migrate

 

Configure the MySQL Database

We will create a CRUD operation on Books. So the user can create, read, update, and delete the books from the database. So, let’s create a model and migration files.

#Step 2: Create a model and migration files.

Since we have set up our database, now let’s take a look at database migrations. Migration is used to store the details about a database table, and it’s properties, so you don’t have to manually create all the tables by going to the database interface or something like phpmyadmin. We can develop migrations using artisan with “make: migration” command.

Type the following command to create a model and migration files.

php artisan make:model Book -m

In laravel, the name of the model has to be singular, and the name of the migration should be plural so it can automatically find the table name. You can find these migration files in database/migrations directory. Laravel by default comes with two migrations namely users and password_resets (all migration files are prepended with a timestamp), which are used for authentication. If you want to create a migration but have a different table name in mind then you can explicitly define the table name with “ — create” flag:

It will create a Book.php file and [timestamp]create_books_table.php migration file.

Now, open the migration file inside the database >> migrations >> [timestamp]create_books_table file and add the following schema inside it.

public function up()
{
     Schema::create('books', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('book_name');
        $table->string('isbn_no');
        $table->integer('book_price');
        $table->timestamps();
     });
}

When you open the create_books_table.php, you will see two methods, up() and down(). up() is used for creating/updating tables, columns, and indexes. The down() method is used for reversing the operation done by up() method.

Inside up() method, We have Schema: create(‘table_name’, callback) method which will be used for creating a new table. Inside the callback, we have $table->bigIncrements(‘id’) which will create an auto_increment integer column with a primary key and argument ‘id’ is the name of the column. Second one is $table->timestamps() which will create two timestamp columns created_at and updated_at. created_at will be filled when a row is created and updated_at when a row is updated. We will add two columns title and body (for the sake of simplicity) but if you want to know the types of the available columns then see the list.

Now, create a table in the database using the following command.

php artisan migrate

 

Laravel 5.8 CRUD Tutorial With Example For Beginner

Above command will run the migrations and create all the tables. It will execute the up() method. If you want to reverse the migrations, you can use migrate: rollback command which will execute down() method like php artisan migrate: rollback.

So, in the database, the table is created successfully.

Now, add the fillable property inside Book.php file.

// Book.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = ['book_name', 'isbn_no', 'book_price'];
}

We can specify properties to modify the behavior of a model. We can write the $table property which is used to determine the name of the table that this model will interact with. By default, It will define the table name as the plural of the model name, e.g., books table for Book model and users table for User model. When you don’t want to use timestamps on your table, then you will also have to specify $timestamps property and set it to false in your Model because Laravel expects your table to have created_at and updated_at timestamp columns.

#Step 3: Create routes and controller

First, create the BookController using the following command.

php artisan make:controller BookController --resource

Note that we have also added a — resource flag which will define six methods inside the BookController namely:

  1. Index (used for displaying a list of Books)
  2. Create (will show a view with a form for creating a Book)
  3. Store (used for creating a Book inside the database. Note: create method submits to store method)
  4. Show (will display a specified Book)
  5. Edit (will show a form for editing a Book. Form will be filled with the existing Book data)
  6. Update (Used for updating a Book inside the database. Note: edit submits to update method)
  7. Destroy (used for deleting a specified Book)

Now, inside routes >> web.php file, add the following line of code.

<?php

// BookController.php

Route::get('/', function () {
    return view('welcome');
});

Route::resource('books', 'BookController');

We can pass dynamic parameters with {} brackets, and you might have noticed that show, update, and destroy has the same url but different methods, so it’s legit. Just like — resource flag, laravel has a method called resource() that will generate all the above routes. You can also use that method instead of specifying them individually like above.

Actually, by adding the following line, we have registered the multiple routes for our application. We can check it using the following command.

php artisan route:list

 

Laravel 5.8 CRUD Tutorial

Okay, now open the BookController.php file, and you can see that all the functions declarations are there.

<?php

// BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BookController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

#Step 4: Create the views

Inside resources >> views folder, create the following three files.

  1. create.blade.php
  2. edit.blade.php
  3. index.blade.php

Also inside the views folder, we also need to create a layout file. So create one file inside the views folder called layout.blade.php. Add the following code inside the layout.blade.php file.

<!-- layout.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel 5.8 CRUD Example Tutorial</title>
  <link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
  <div class="container">
    @yield('content')
  </div>
  <script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>

So basically, this file is our main template file, and all the other view files will extend this file. Here, we have already included the Bootstrap 4 by adding the app.css.

Next step would be to code the create.blade.php file. So write the following code inside it.

<!-- create.blade.php -->

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Book
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('books.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Book Name:</label>
              <input type="text" class="form-control" name="book_name"/>
          </div>
          <div class="form-group">
              <label for="price">Book ISBN Number :</label>
              <input type="text" class="form-control" name="isbn_no"/>
          </div>
          <div class="form-group">
              <label for="quantity">Book Price :</label>
              <input type="text" class="form-control" name="book_price"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Book</button>
      </form>
  </div>
</div>
@endsection

Okay, now we need to open the BookController.php file, and on the create function, we need to return a view, and that is the create.blade.php file.

// BookController.php

public function create()
{
   return view('create');
}

Save the file and start the Laravel development server using the following command.

php artisan serve

Go to the http://localhost:8000/books/create. 

You can see something like this.

Create the views

#Step 5: Add Validation rules and save data

In this step, we will add the Laravel Validation.

Now, the first step inside the BookController.php is that import the namespace of Book model inside the BookController.php file.

// BookController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;

Now, write the following code inside the BookController.php file’s store() function.

// BookController.php

public function store(Request $request)
{
    $validatedData = $request->validate([
         'book_name' => 'required|max:255',
         'isbn_no' => 'required|alpha_num',
         'book_price' => 'required|numeric',
     ]);
     $book = Book::create($validatedData);

     return redirect('/books')->with('success', 'Book is successfully saved');
}

Here, what we have done is first check for all three fields of the form.

If any of the rules are failed by the incoming data, then it will directly go to the form with the error messages.

Store method has $request object as a parameter which will be used to access form data. The first thing you want to do is validate the form data. We can use the $request->validate() method for validation, which will receive an array of validation rules.

Validation rules is an associative array. Key will be the field_name and value with being the validation rules. The second parameter is an optional array for custom validation messages. Rules are separated with pipe sign “|.” We are using the most basic validation rules. First is “required” which means the field_name should not be empty (“nullable” rule is vice versa), “string” means it should be a string value, “min” is the limit of minimum characters for a string in an input field and “max” is the maximum characters. “unique:table,column” with see if the same value does not exists in the database (comes handy for storing emails or any other unique data).

If validation fails, then it will redirect us back. After validation, we are creating a new book and save that book in the database.

We need to loop through that error messages inside the create.blade.php file which we have already done it.

If you leave all the form fields empty, then you will find an error message like this image.

Laravel 5.8 validation example

Now, if you fill the form fields correctly, then it will create a new row in the database. I have created a new book.

Laravel Create Example

Some Methods for accessing form data:

$request->input('field_name'); // access an input field
$request->has('field_name'); // check if field exists
$request->title; // dynamically access input fields
request('key') // you can use this global helper if needed inside a view

Helpful redirecting methods:

return redirect('/books'); // to a specific url
return redirect(url('/books')); // to a specific url with url helper
return redirect(url()->previous()); // to a previous url
return redirect()->back(); // redirect back (same as above)

#Step 6: Display the data.

Now, we need to write the BookController’s index function to return the index view with the data fetched from the database. Write the following code inside the index() function.

// BookController.php

public function index()
{
     $books = Book::all();

     return view('index', compact('books'));
}

Okay, now create the file called index.blade.php inside the views folder and add the following code.

<!-- index.blade.php -->

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="uper">
  @if(session()->get('success'))
    <div class="alert alert-success">
      {{ session()->get('success') }}  
    </div><br />
  @endif
  <table class="table table-striped">
    <thead>
        <tr>
          <td>ID</td>
          <td>Book Name</td>
          <td>ISBN Number</td>
          <td>Book Price</td>
          <td colspan="2">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($books as $book)
        <tr>
            <td>{{$book->id}}</td>
            <td>{{$book->book_name}}</td>
            <td>{{$book->isbn_no}}</td>
            <td>{{$book->book_price}}</td>
            <td><a href="{{ route('books.edit',$book->id)}}" class="btn btn-primary">Edit</a></td>
            <td>
                <form action="{{ route('books.destroy', $book->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

Here, we have looped through the books array and display the data in the tabular format.

Also, we have added two buttons for edit and delete operation.

#Step 7: Create Edit and Update Operation

First, we need to add the following code inside the BookController.php file’s edit function.

// BookController.php

public function edit($id)
{
    $book = Book::findOrFail($id);

    return view('edit', compact('book'));
}

Now, create a new file inside the views folder called edit.blade.php and add the following code.

<!-- edit.blade.php -->

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Edit Book
  </div>
  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('books.update', $book->id) }}">
          <div class="form-group">
              @csrf
              @method('PATCH')
              <label for="name">Book Name:</label>
              <input type="text" class="form-control" name="book_name" value="{{$book->book_name}}"/>
          </div>
          <div class="form-group">
              <label for="price">Book ISBN Number :</label>
              <input type="text" class="form-control" name="isbn_no" value="{{$book->isbn_no}}"/>
          </div>
          <div class="form-group">
              <label for="quantity">Book Price :</label>
              <input type="text" class="form-control" name="book_price" value="{{$book->book_price}}"/>
          </div>
          <button type="submit" class="btn btn-primary">Update Book</button>
      </form>
  </div>
</div>
@endsection

In this file, you can show the values of the particular row using its unique id inside the form fields.

So, when you hit this URL: http://localhost:8000/books/1/edit, you will see something like below image.

 

Edit Functionality in Laravel

Now, add the following code inside the BookController’s update() function.

// BookController.php

public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        Book::whereId($id)->update($validatedData);

        return redirect('/books')->with('success', 'Book is successfully updated');
    }

So now, you can edit and update the data into the database successfully.

#Step 8: Create Delete Functionality

Write the following code inside the BookController’s destroy function.

// BookController.php

public function destroy($id)
    {
        $book = Book::findOrFail($id);
        $book->delete();

        return redirect('/books')->with('success', 'Book is successfully deleted');
    }

Now, go to this URL: http://localhost:8000/books and try to delete the book.

You can see that you have successfully deleted the book.

So, our complete BookController.php code looks like below.

<?php

// BookController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;

class BookController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $books = Book::all();

        return view('index', compact('books'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        $book = Book::create($validatedData);

        return redirect('/books')->with('success', 'Book is successfully saved');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $book = Book::findOrFail($id);

        return view('edit', compact('book'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'book_name' => 'required|max:255',
            'isbn_no' => 'required|alpha_num',
            'book_price' => 'required|numeric',
        ]);
        Book::whereId($id)->update($validatedData);

        return redirect('/books')->with('success', 'Book is successfully updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $book = Book::findOrFail($id);
        $book->delete();

        return redirect('/books')->with('success', 'Book is successfully deleted');
    }
}

So, we have completed a Laravel 5.8 CRUD operations tutorial with the example from scratch.

If you are interested in the FrontEnd framework like Vue.js then check out my Vue Laravel CRUD example and Angular Laravel Tutorial Example.

I have put this code on Github so you can check it out as well.

GITHUB CODE

The post Laravel 5.8 CRUD Tutorial With Example For Beginners appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/08/laravel-5-8-crud-tutorial-with-example-for-beginners/feed/ 16
Laravel Stripe Payment Gateway Integration Tutorial With Example https://appdividend.com/2018/12/05/laravel-stripe-payment-gateway-integration-tutorial-with-example/ https://appdividend.com/2018/12/05/laravel-stripe-payment-gateway-integration-tutorial-with-example/#comments Wed, 05 Dec 2018 13:11:06 +0000 http://localhost/wordpress/?p=2441 Laravel Stripe Payment Example Tutorial

Laravel Stripe Payment Gateway Integration Tutorial With Example is today’s leading topic. We will use the Cashier package to integrate Stripe Payment Gateway in Laravel. The demand for Saas based platform is increasing day by day and nowadays building a subscription-based system is universal. So to make it easy on the backend like Laravel, we […]

The post Laravel Stripe Payment Gateway Integration Tutorial With Example appeared first on AppDividend.

]]>
Laravel Stripe Payment Example Tutorial

Laravel Stripe Payment Gateway Integration Tutorial With Example is today’s leading topic. We will use the Cashier package to integrate Stripe Payment Gateway in Laravel. The demand for Saas based platform is increasing day by day and nowadays building a subscription-based system is universal. So to make it easy on the backend like Laravel, we do need some packages that can help us build scalable, securable, and reliable web applications. Laravel Cashier makes it very simple to integrate Payment Gateway like Stripe. So let us see how we can integrate stripe in Laravel on Subscription based system.

Laravel Stripe Payment Gateway Integration

Let us first install and configure Laravel 5.7

Step 1: Install and configure Laravel 5.7

Type the following command.

laravel new stripesub

Go to the project folder and open the project in an editor. I am using VSCode.

cd stripesub && code .

Install the js dependencies using the following command.

npm install

Install the Cashier package for Stripe dependencies.

composer require laravel/cashier

Also, create an authentication scaffold.

php artisan make:auth

Step 2: Create an essential database migrations

Before using Cashier, we’ll also need to prepare the database. We need to add several columns to your users’ table and create new subscriptions and plans table to hold all of our customer’s subscriptions.

So, first go to the create_users_table.php and add the following schema.

$table->string('stripe_id')->nullable()->collation('utf8mb4_bin');
$table->string('card_brand')->nullable();
$table->string('card_last_four', 4)->nullable();
$table->timestamp('trial_ends_at')->nullable();

Your schema now looks like this.

public function up()
{
     Schema::create('users', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');
         $table->string('email')->unique();
         $table->timestamp('email_verified_at')->nullable();
         $table->string('password');
         $table->string('stripe_id')->nullable()->collation('utf8mb4_bin');
         $table->string('card_brand')->nullable();
         $table->string('card_last_four', 4)->nullable();
         $table->timestamp('trial_ends_at')->nullable();
         $table->rememberToken();
         $table->timestamps();
     });
}

Now, create two more migrations files.

php artisan make:migration create_subscriptions_table
php artisan make:migration create_plans_table

Now, write the schema on both of the files.

First, add the following schema inside the create_subscriptions_table.php file.

public function up()
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->string('name');
            $table->string('stripe_id')->collation('utf8mb4_bin');
            $table->string('stripe_plan');
            $table->integer('quantity');
            $table->timestamp('trial_ends_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->timestamps();
        });
    }

Write the following schema inside the create_plans_table.php file.

public function up()
    {
        Schema::create('plans', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('stripe_plan');
            $table->float('cost');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

Save the file and go to the terminal and migrate tables.

php artisan migrate

Now, add two plans manually on the plans table like this.

 

Laravel Stripe Payment Gateway Integration Tutorial With Example

Step 3: Get and Set Stripe API Keys

First, you need to create an account on Stripe. You can do it on here. Then after login to your account, you will find a Test dashboard.

Now, click on the Developers link on the left sidebar. In the submenu, you can find the API keys item. Click on that item, and you will be redirected to this page.

 

Stripe API keys

Here, you can find the Publishable Key or Stripe Key and Secret Key.

You need to add these keys inside the .env file in our project.

// .env

STRIPE_KEY=your key here
STRIPE_SECRET=your secret here

Finally, you should configure your Stripe key in your services.php configuration file. You can retrieve your Stripe API keys from the Stripe control panel.

// services.php

'stripe' => [
    'model'  => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Also, you need to add the Billable Trait inside the User.php model.

// User.php

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

Step 4: Create Plans on Stripe Dashboard

You can create a plan through Laravel but that will take some time, and our motto is to accept the payment through stripe. So we will create the plans manually on Stripe Dashboard.

First, go to the Billing >> Products link and right now, there are no products available. So we need to create two products. Here products mean plans. So we will create two plans.

  1. Basic
  2. Professional

Create and assign the values same as we have assigned the values on the Plans table in our Laravel application. After creating two plans, your products look like this.

 

Laravel Subscription Based System Using Stripe Payment

Step 5: Display Plans on Frontend

First, define the routes for our application inside the routes >> web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
});

We have taken the auth middleware to protect the routes related to payment and home.

Now, create the Plan.php model and PlanController.php file.

php artisan make:model Plan
php artisan make:controller PlanController

Define the index method inside the PlanController.

// PlanController.php

use App\Plan;

public function index()
{
        $plans = Plan::all();
        return view('plans.index', compact('plans'));
}

Now, inside the resources >> views folder, create one folder called plans and inside that folder, create one file called index.blade.php file. Write the following code.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">Plans</div>
                <div class="card-body">
                    <ul class="list-group">
                        @foreach($plans as $plan)
                        <li class="list-group-item clearfix">
                            <div class="pull-left">
                                <h5>{{ $plan->name }}</h5>
                                <h5>${{ number_format($plan->cost, 2) }} monthly</h5>
                                <h5>{{ $plan->description }}</h5>
                                <a href="" class="btn btn-outline-dark pull-right">Choose</a>
                            </div>
                        </li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, register one user on Laravel application and go to this URL: http://stripesub.test/plans

You will find the plans like this.

 

Laravel Saas Tutorial

Step 6: Show the plan

So, when the user chooses the plan, we need to redirect the user to a particular plan page.

Define one more route inside the routes >> web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
    Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show');
});

Now, by default, RouteModelBinding works with the ID of the model. But we will not pass the ID to show the particular plan instead we will pass the slug. So we need to define it inside the Plan.php model.

<?php

// Plan.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plan extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'stripe_plan',
        'cost',
        'description'
    ];

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

Here, we have defined the function called getRouteKeyName. So based on this function, now we can fetch the record based on the slug and not based on the ID. That is why we have taken the slug field as a unique field in the database.

Now, define the show() function inside the PlanController.php file.

// PlanController.php

public function show(Plan $plan, Request $request)
{
     return view('plans.show', compact('plan'));
}

Next step is to create a view file called show.blade.php inside the resources >> views >> plans folder. Add the following code inside the show.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ $plan->name }}</div>
                <div class="card-body">
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, we will display the Payment Form on this page.

Step 7: Display the Payment Form

For this example, I am using Card Element. You can find it on official Stripe Documentation. It is securely collect sensitive card details using Elements, our pre-built UI components.

 

Stripe Payment Form Example

Now, we need to include the External JS files in our project. For that, we need to modify the resources >> views >> layouts >> app.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                            </li>
                            <li class="nav-item">
                                @if (Route::has('register'))
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                @endif
                            </li>
                        @else
                          <li class="nav-item">      
                            <a class="nav-link" href="{{ route('plans.index') }}">{{ __('Plans') }}</a>
                          </li>
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    @yield('scripts')
</body>
</html>

Here, we have defined one navigation link called plans and also add one section for scripts. So, now we can add the Javascript per pagewise using @yield directive.

Next step is to write the Card Element inside the show.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="">
                <p>You will be charged ${{ number_format($plan->cost, 2) }} for {{ $plan->name }} Plan</p>
            </div>
            <div class="card">
                <form action="#" method="post" id="payment-form">
                    @csrf                    
                    <div class="form-group">
                        <div class="card-header">
                            <label for="card-element">
                                Enter your credit card information
                            </label>
                        </div>
                        <div class="card-body">
                            <div id="card-element">
                            <!-- A Stripe Element will be inserted here. -->
                            </div>
                            <!-- Used to display form errors. -->
                            <div id="card-errors" role="alert"></div>
                            <input type="hidden" name="plan" value="{{ $plan->id }}" />
                        </div>
                    </div>
                    <div class="card-footer">
                        <button class="btn btn-dark" type="submit">Pay</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection
@section('scripts')
<script src="https://js.stripe.com/v3/"></script>
<script>
    // Create a Stripe client.
var stripe = Stripe('{{ env("STRIPE_KEY") }}');

// Create an instance of Elements.
var elements = stripe.elements();

// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
  base: {
    color: '#32325d',
    lineHeight: '18px',
    fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
    fontSmoothing: 'antialiased',
    fontSize: '16px',
    '::placeholder': {
      color: '#aab7c4'
    }
  },
  invalid: {
    color: '#fa755a',
    iconColor: '#fa755a'
  }
};

// Create an instance of the card Element.
var card = elements.create('card', {style: style});

// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');

// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();

  stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the user if there was an error.
      var errorElement = document.getElementById('card-errors');
      errorElement.textContent = result.error.message;
    } else {
      // Send the token to your server.
      stripeTokenHandler(result.token);
    }
  });
});

// Submit the form with the token ID.
function stripeTokenHandler(token) {
  // Insert the token ID into the form so it gets submitted to the server
  var form = document.getElementById('payment-form');
  var hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);

  // Submit the form
  form.submit();
}
</script>
@endsection

Here, we have used the Card element and Javascript to display the form.

Now, add the link to this page inside the index.blade.php file.

// index.blade.php

<a href="{{ route('plans.show', $plan->slug) }}" class="btn btn-outline-dark pull-right">Choose</a>

So, it will be redirected to the page like this.

 

Stripe Payment Gateway Integration in Laravel

So, here we need to enter the following details. You can enter the details like below inputs.

  1. Card Number: 4242 4242 4242 4242
  2. Expiration Date: 10/21 or whatever you like from the future of today’s date
  3. CVC: whatever you like
  4. Zipcode: whatever you like

These are dummy details, but these details generally used in sandbox account to check the application.

Right now nothing will happen because we need to define the form action to store the data inside the database tables. So let us define the post route.

Step 8: Save the subscriptions and accept payment

Define the final route inside the web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
    Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show');
    Route::post('/subscription', 'SubscriptionController@create')->name('subscription.create');
});

We have defined the POST route for subscriptions. Now, create SubscriptionController using the following command.

php artisan make:controller SubscriptionController

Now, add a POST route inside the show.blade.php file when we post the data to the server.

// show.blade.php

<form action="{{ route('subscription.create') }}" method="post" id="payment-form">

Inside that controller, we need to define one function called create().

<?php

// SubscriptionController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Plan;

class SubscriptionController extends Controller
{
    public function create(Request $request, Plan $plan)
    {
        $plan = Plan::findOrFail($request->get('plan'));
        
        $request->user()
            ->newSubscription('main', $plan->stripe_plan)
            ->create($request->stripeToken);
        
        return redirect()->route('home')->with('success', 'Your plan subscribed successfully');
    }
}

Here, we are creating the subscription for registered User and charge him.

First, we have to fetch the plan according to the id. Then we need to pass that plan to the newSubscription() function and create a subscription.

So, here we have used the Billable trait’s subscribedToPlan() method and pass the first parameter plan and the second parameter main.

We are creating a new Subscription, if the payment made successfully then, it would redirect to the HomePage with a  success message.

Write the following code inside the home.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            @if(session()->get('success'))
                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>
            @endif
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    Welcome to the Dashboard
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So, if your all of the configurations are right, then you should go to any of the plans and try to subscribe to the plan. If you are redirecting to the homepage, then you are almost done.

You can see that one database entry inside the subscriptions table is there.

 

Laravel Saas Example

Your user’s table also has been updated as you can see some field’s details is updated.

You can check the Stripe Dashboard as well. As we have subscribed the 50$ Professional Plan.

 

Stripe Payment Example

Step 9: Security Tweaks

Now, we need to keep in mind one thing that if the user is already subscribed to one plan, then we need the user to prevent to choose that plan. So, we need to add one condition on the choose button.

So, add the condition inside the index.blade.php file.

@if(!auth()->user()->subscribedToPlan($plan->stripe_plan, 'main'))
    <a href="{{ route('plans.show', $plan->slug) }}" class="btn btn-outline-dark pull-right">Choose</a>
@endif

Also, we need to add the condition inside the PlanController.php file’s show() function.

// PlanController.php

public function show(Plan $plan, Request $request)
{
        if($request->user()->subscribedToPlan($plan->stripe_plan, 'main')) {
            return redirect()->route('home')->with('success', 'You have already subscribed the plan');
        }
        return view('plans.show', compact('plan'));
 }

Also, we need to do the same thing inside the SubscriptionController’s create() method.

// SubscriptionController.php

public function create(Request $request, Plan $plan)
{
        if($request->user()->subscribedToPlan($plan->stripe_plan, 'main')) {
            return redirect()->route('home')->with('success', 'You have already subscribed the plan');
        }
        $plan = Plan::findOrFail($request->get('plan'));
        
        $request->user()
            ->newSubscription('main', $plan->stripe_plan)
            ->create($request->stripeToken);
        
        return redirect()->route('home')->with('success', 'Your plan subscribed successfully');
}

Save the file, and now you are good to go. I am putting this Laravel Stripe Payment Gateway Integration Tutorial’s whole code on Github.

Finally, Laravel Stripe Payment Gateway Integration Tutorial article is over. There are still so many things that we can do with the project. But for basic understanding, this is enough. Thanks.

Github Code

The post Laravel Stripe Payment Gateway Integration Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/05/laravel-stripe-payment-gateway-integration-tutorial-with-example/feed/ 14
Laravel Cashier Braintree Payment Gateway Tutorial With Example https://appdividend.com/2018/12/04/laravel-cashier-braintree-payment-gateway/ https://appdividend.com/2018/12/04/laravel-cashier-braintree-payment-gateway/#comments Tue, 04 Dec 2018 03:56:54 +0000 http://localhost/wordpress/?p=2410 Laravel 5.7 Payment Gateway Tutorial With Example Using Saas application

In this tutorial, we will see Laravel Cashier Braintree Payment Gateway Tutorial With Example We will build a Subscription based Platform in which the user can choose a plan, and according to that, he will be charged. We use Braintree for this demo, and we will discuss the stripe in the next tutorial. So, we […]

The post Laravel Cashier Braintree Payment Gateway Tutorial With Example appeared first on AppDividend.

]]>
Laravel 5.7 Payment Gateway Tutorial With Example Using Saas application

In this tutorial, we will see Laravel Cashier Braintree Payment Gateway Tutorial With Example We will build a Subscription based Platform in which the user can choose a plan, and according to that, he will be charged. We use Braintree for this demo, and we will discuss the stripe in the next tutorial. So, we will build a simple payment gateway in which a user can charge according to their selected plan. It is a straightforward system to work with, and for that, we need to create a developer account at Braintree. So, if you have not created yet, then please go to this link.

Laravel Cashier Braintree Payment Gateway

Integrate payment gateway in any web application used to be a very tough task. But nowadays, there are lots of SDKs available to work with that is why it is effortless to integrate any payment gateway to any web application. Now, you can find the Official Laravel Documentation to integrate Braintree here.

Braintree Caveats

For many operations, the Stripe and Braintree implementations of the Cashier function is the same. Both services provide the subscription billing with the credit cards, but Braintree also supports the payments via PayPal. We will not use Paypal for this example. However, Braintree also lacks some features that are supported by the Stripe. You should keep the following things in mind when deciding to use Stripe or Braintree:

  • Braintree supports PayPal while Stripe does not.
  • Braintree does not support the increment and decrement methods on subscriptions. This is a Braintree limitation, not a Cashier limitation.
  • Braintree does not support percentage based discounts. This is a Braintree limitation, not a Cashier limitation.

Let us start this small project by installing the Laravel Framework. I am using Laravel 5.7 for this example.

Step 1: Install and configure Laravel

Install Laravel using the following command.

laravel new subscription

Now, go inside the project folder and configure the database inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=subscription
DB_USERNAME=root
DB_PASSWORD=root

Also, install the npm dependencies using the following command.

npm install

Compile the CSS and JS files.

npm run dev

Also, create the standard authentication using the following command.

php artisan make:auth

Step 2: Install and configure Braintree package

Next step is to install the Laravel Cashier package. So let us install that.

composer require "laravel/cashier-braintree":"~2.0"

Next step is to register the Laravel\Cashier\CashierServiceProvider  service provider in your config/app.php configuration file.

...
Laravel\Cashier\CashierServiceProvider::class,
...

Now, we need to create and modify the database migrations.

First, edit the create_users_table.php file and add the following fields inside the schema.

Schema::table('users', function ($table) {
    $table->string('braintree_id')->nullable();
    $table->string('paypal_email')->nullable();
    $table->string('card_brand')->nullable();
    $table->string('card_last_four')->nullable();
    $table->timestamp('trial_ends_at')->nullable();
});

So, our final create_users_table.php file looks like below.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('braintree_id')->nullable();
            $table->string('paypal_email')->nullable();
            $table->string('card_brand')->nullable();
            $table->string('card_last_four')->nullable();
            $table->timestamp('trial_ends_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Also, we need to create two more migrations file. To create the files, hit the following commands.

php artisan make:migration create_plans_table
php artisan make:migration create_subscriptions_table

Now, write the following schemas inside it.

<?php

// create_subscriptions_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSubsriptionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('subsriptions', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('user_id');
          $table->string('name');
          $table->string('braintree_id');
          $table->string('braintree_plan');
          $table->integer('quantity');
          $table->timestamp('trial_ends_at')->nullable();
          $table->timestamp('ends_at')->nullable();
          $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('subsriptions');
    }
}

And the following is plans table schema.

<?php

// create_plans_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePlansTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('plans', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('braintree_plan');
            $table->float('cost');
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('plans');
    }
}

Now go to the terminal and create the tables using the following command.

php artisan migrate

It will create the tables.

 

Laravel Cashier Braintree Payment Gateway Tutorial With Example

Now, add the Billable Trait inside the User.php model.

// User.php

use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use Billable;
}

Step 3: Grab and add API keys for Braintree

Now, if you have not created a developer account at Braintree, then please create one.

After that, you will be redirected to the Dashboard and then go to the Account >> My User and click the View Authorizations link under the API Keys, Tokenization Keys, Encryption Keys section.

 

API Keys, Tokenization Keys, Encryption Keys

After clicking the View Authorizations link, you will be redirected to your Sandbox API Keys page.

 

Laravel Braintree Payment Gateway Example Tutorial

Now, you need to click the View links inside the table, and now you can see your following keys and data.

  1. Your Public Key
  2. Your Private Key
  3. Your Environment
  4. Your Merchant Id

You need to add these keys inside your .env file.

BRAINTREE_ENV=sandbox
BRAINTREE_MERCHANT_ID=your merchant id
BRAINTREE_PUBLIC_KEY=your public key
BRAINTREE_PRIVATE_KEY=your private key

Next step is that you should configure the following options inside your services.php file.

// services.php

'braintree' => [
    'model'  => App\User::class,
    'environment' => env('BRAINTREE_ENV'),
    'merchant_id' => env('BRAINTREE_MERCHANT_ID'),
    'public_key' => env('BRAINTREE_PUBLIC_KEY'),
    'private_key' => env('BRAINTREE_PRIVATE_KEY'),
],

Then you should add the following Braintree SDK calls to your AppServiceProvider’s boot method.

// AppServiceProvider.php

use Braintree_Configuration;

public function boot()
{
      Braintree_Configuration::environment(env('BRAINTREE_ENV'));
      Braintree_Configuration::merchantId(env('BRAINTREE_MERCHANT_ID'));
      Braintree_Configuration::publicKey(env('BRAINTREE_PUBLIC_KEY'));
      Braintree_Configuration::privateKey(env('BRAINTREE_PRIVATE_KEY'));
}

You can also set the currency. Dollar($) is by default.

You can change the default currency by calling the Cashier::useCurrency method from within the boot method of one of your service providers. In our case we have used the AppServiceProvider. The useCurrency method accepts two string parameters: the currency and the currency’s symbol.

// AppServiceProvider.php

use Laravel\Cashier\Cashier;

Cashier::useCurrency('eur', '€');

Step 4: Create plans on Braintree dashboard

Now, for this example, we will create only two plans. You can create as per your requirement. You can find the plans inside your dashboard on the left sidebar.

I have created two plans.

  1. Basic
  2. Professional

 

Laravel Subscription Based System

Also, you need to add the plans manually inside the plans table inside MySQL.

 

Laravel Braintree Example

Make sure both plans have the same names as on MySQL and Braintree dashboard.

Step 5: Display plans on Frontend

First, define the routes for our application inside the routes >> web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
});

We have taken the auth middleware to protect the routes related to payment and home.

Now, create the Plan.php model and PlanController.php file.

php artisan make:model Plan
php artisan make:controller PlanController

Define the index method inside the PlanController.

// PlanController.php

use App\Plan;

public function index()
{
        $plans = Plan::all();
        return view('plans.index', compact('plans'));
}

Now, inside the resources >> views folder, create one folder called plans and inside that folder, create one file called index.blade.php file. Write the following code.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">Plans</div>
                <div class="card-body">
                    <ul class="list-group">
                        @foreach($plans as $plan)
                        <li class="list-group-item clearfix">
                            <div class="pull-left">
                                <h5>{{ $plan->name }}</h5>
                                <h5>${{ number_format($plan->cost, 2) }} monthly</h5>
                                <h5>{{ $plan->description }}</h5>
                                
                                <a href="" class="btn btn-outline-dark pull-right">Choose</a>
                                
                            </div>
                        </li>
                        @endforeach
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Save the file and navigate to the URL: http://subscription.test/plans. If you have not registered yet, then please register one user in our application.

You will see something like this.

Laravel Payment Example

 

So, we have successfully displayed the plans from the database. Now, the next step is when a user chooses the plan, you will redirect to a page from where a user can be charged for that plan.

Step 6: Show the plan

So, when the user chooses the plan, we need to redirect the user to a particular plan page.

Define one more route inside the routes >> web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
    Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show');
});

Now, by default, RouteModelBinding works with the ID of the model. But we will not pass the ID to show the particular plan instead we will pass the slug. So we need to define it inside the Plan.php model. Also, define the fillable fields as well.

<?php

// Plan.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plan extends Model
{
	protected $fillable = [
		'name',
		'slug',
		'braintree_plan',
		'cost',
		'description'
	];

	public function getRouteKeyName()
	{
		return 'slug';
	}
}

Here, we have defined the function called getRouteKeyName. So based on this function, now we can fetch the record based on the slug and not based on the ID. That is why we have taken the slug field as a unique field in the database.

Now, define the show() function inside the PlanController.php file.

// PlanController.php

public function show(Plan $plan, Request $request)
{
     return view('plans.show', compact('plan'));
}

Next step is to create a view file called show.blade.php inside the resources >> views >> plans folder. Add the following code inside the show.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ $plan->name }}</div>
                <div class="card-body">
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So, here, we will display the payment form.

Step 7: Display the Payment Form

For displaying the Payment Form, we will use the Drop-in UI. You can find the complete documentation here. We are using Version 2 of the Drop-in UI. There is version 3 but let us stick with version 2 for this example. Now, we are implementing the Client Side configuration. Configure the container and from where the Drop-in UI will add the payment method nonce. Make sure to replace CLIENT_AUTHORIZATION with your generated client token.

Now, we need to include the External JS files in our project. For that, we need to modify the resources >> views >> layouts >> app.blade.php file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                            </li>
                            <li class="nav-item">
                                @if (Route::has('register'))
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                @endif
                            </li>
                        @else
                          <li class="nav-item">      
                            <a class="nav-link" href="{{ route('plans.index') }}">{{ __('Plans') }}</a>
                          </li>
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    @yield('scripts');
</body>
</html>

Here, we have defined one navigation link called plans and also add one section for scripts. So, now we can add the Javascript per pagewise using @yield directive.

Also, we need to fetch the Client Token for authorization. So we will fetch that token from Backend using AJAX request.

So, define one route inside the web.php file.

// web.php

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
    Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show');
    Route::get('/braintree/token', 'BraintreeTokenController@index')->name('token');
});

Create a new Controller called BraintreeTokenController using the following command.

php artisan make:controller BraintreeTokenController

Write the following code inside the BraintreeTokenController.php file.

<?php

// BraintreeTokenController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Braintree_ClientToken;

class BraintreeTokenController extends Controller
{
    public function index()
    {
        return response()->json([
            'data' => [
                'token' => Braintree_ClientToken::generate()
            ]
        ]);
    }
}

The index() function returns the ClientToken to the Clientside JS file, and now we can authorize our Laravel application with the Braintree developer account.

So, write the final code inside the show.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ $plan->name }}</div>
                <div class="card-body">
                <form method="post" action="{{ route('subscription.create') }}">
                    @csrf
                    <div id="dropin-container"></div>
                    <hr />
                    <input type="hidden" name="plan" value="{{ $plan->id }}" />
                    <button type="submit" class="btn btn-outline-dark d-none" id="payment-button">Pay</button>
                </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script src="https://js.braintreegateway.com/js/braintree-2.32.1.min.js"></script>
<script>
    jQuery.ajax({
        url: "{{ route('token') }}",
    })
    .done(function(res) {
        braintree.setup(res.data.token, 'dropin', {
            container: 'dropin-container',
            onReady: function() {
                jQuery('#payment-button').removeClass('d-none')
            }
        });
    });
</script>
@endsection

So, when the document is loaded, we will send an Ajax request to the Laravel server and get the Client Auth token. From that token, included js will generate the Payment Form. We defined the form like this.

<form method="post" action="">
        @csrf
        <div id="dropin-container"></div>
        <hr />
        <input type="hidden" name="plan" value="{{ $plan->id }}" />
        <button type="submit" class="btn btn-outline-dark d-none" id="payment-button">Pay</button>
</form>

Also, write the Javascript like this.

@section('scripts')
<script src="https://js.braintreegateway.com/js/braintree-2.32.1.min.js"></script>
<script>
    jQuery.ajax({
        url: "{{ route('token') }}",
    })
    .done(function(res) {
        braintree.setup(res.data.token, 'dropin', {
            container: 'dropin-container',
            onReady: function() {
                jQuery('#payment-button').removeClass('d-none')
            }
        });
    });
</script>
@endsection

So, when the request succeeds, it will return the token, and we use that token to create a Payment Form. The form looks like this.

 

Laravel 5.7 Payment Tutorial With Example

So, here we need to enter the two details. You can enter the details like below inputs.

  1. Card Number: 4242 4242 4242 4242
  2. Expiration Date: 10/21 or whatever you like

These are dummy details, but these details generally used in sandbox account to check the application.

Right now nothing will happen because we need to define the form action to store the data inside the database tables. So let us define the post route.

Step 8: Save the plan details

Define the final route inside the web.php file.

<?php

// web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::group(['middleware' => 'auth'], function() {
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/plans', 'PlanController@index')->name('plans.index');
    Route::get('/plan/{plan}', 'PlanController@show')->name('plans.show');
    Route::get('/braintree/token', 'BraintreeTokenController@index')->name('token');
    Route::post('/subscription', 'SubscriptionController@create')->name('subscription.create');
});

We have defined the post route for the subscription details. Now, create SubscriptionController using the following command.

php artisan make:controller SubscriptionController

Inside that controller, we need to define one function called create().

<?php

// SubscriptionController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Plan;

class SubscriptionController extends Controller
{
    public function create(Request $request, Plan $plan)
    {
        $plan = Plan::findOrFail($request->get('plan'));
        
        $request->user()
            ->newSubscription('main', $plan->braintree_plan)
            ->create($request->payment_method_nonce);
        
        return redirect()->route('home')->with('success', 'Your plan subscribed successfully');
    }
}

First, we have to fetch the plan according to the id. Then we need to pass that plan to the subscribedToPlan() function.

So, here we have used the Billable trait’s subscribedToPlan() method and pass the first parameter plan and the second parameter main.

We are creating a new Subscription, and if the payment made successfully then, it would redirect to the HomePage with a  success message.

Write the following code inside the home.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            @if(session()->get('success'))
                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>
            @endif
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                    You are logged in!
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So, if your all of the configurations are right, then you should go to any of the plans and try to subscribe to the plan. If you are redirecting to the homepage, then you are almost done.

 

Laravel Saas Example

You can see that one database entry inside the subscriptions table is there.

 

Laravel Saas Tutorial

That means, we have successfully subscribed the Professional plan. Also, there is updation on the user’s table. We have already added some more fields.

You can see inside your Dashboard that Sales and Transaction volume is there. So, our Laravel Cashier Braintree Payment Gateway Tutorial With Example is almost complete.

Step 9: Security Tweaks

Now, we need to keep in mind one thing that if the user is already subscribed to one plan, then we need the user to prevent to choose that plan. So, we need to add one condition on the choose button.

So, add the condition inside the index.blade.php file.

@if(!auth()->user()->subscribedToPlan($plan->braintree_plan, 'main'))
     <a href="{{ route('plans.show', $plan->slug) }}" class="btn btn-outline-dark pull-right">Choose</a>
@endif

Also, we need to add the condition inside the PlanController.php file’s show() function.

// PlanController.php

public function show(Plan $plan, Request $request)
{
    if($request->user()->subscribedToPlan($plan->braintree_plan, 'main')) {
            return redirect()->route('home')->with('success', 'You have already subscribed the plan');
    }
    return view('plans.show', compact('plan'));
}

Also, we need to do the same thing inside the SubscriptionController’s create() method.

// SubscriptionController.php

public function create(Request $request, Plan $plan)
{
        if($request->user()->subscribedToPlan($plan->braintree_plan, 'main')) {
            return redirect()->route('home');
        }

        $plan = Plan::findOrFail($request->get('plan'));
        
        $request->user()
            ->newSubscription('main', $plan->braintree_plan)
            ->create($request->payment_method_nonce);
        
        return redirect()->route('home')->with('success', 'Your plan subscribed successfully');
}

Save the file, and now you are good to go. I am putting this Laravel Cashier Braintree Payment Gateway Tutorial’s whole code on Github.

Finally, Laravel Cashier Braintree Payment Gateway Tutorial With Example article is over. There are still so many things that we can do with the project. But for basic understanding, this is enough. Thanks.

Github Code

 

The post Laravel Cashier Braintree Payment Gateway Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/12/04/laravel-cashier-braintree-payment-gateway/feed/ 3