Laravel – AppDividend https://appdividend.com Latest Code Tutorials Wed, 20 Feb 2019 17:29:13 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel – AppDividend https://appdividend.com 32 32 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/ 3
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/#respond 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/ 0
How To Install October CMS on Mac https://appdividend.com/2018/11/30/how-to-install-october-cms-on-mac/ https://appdividend.com/2018/11/30/how-to-install-october-cms-on-mac/#comments Fri, 30 Nov 2018 19:09:41 +0000 http://localhost/wordpress/?p=2388 Laravel based CMS - OctoberCMS

How To Install October CMS on Mac is today’s leading topic. October CMS is built on Laravel  Framework, the best existing PHP framework. Laravel framework includes all of the tools and classes that are necessary for making the quality websites and applications. OctoberCMS adds even more power to Laravel with the collection of simple and flexible features. Development with […]

The post How To Install October CMS on Mac appeared first on AppDividend.

]]>
Laravel based CMS - OctoberCMS

How To Install October CMS on Mac is today’s leading topic. October CMS is built on Laravel  Framework, the best existing PHP framework. Laravel framework includes all of the tools and classes that are necessary for making the quality websites and applications. OctoberCMS adds even more power to Laravel with the collection of simple and flexible features. Development with October can easily be adapted to any existing team workflow. Use your favorite version control system for storing and deploying website themes and plugins. You can build any websites or web apps with OctoberCMS from simple promotional sites to high load social networks.

October CMS Features

There are many features of October CMS. I will be showing you one by one.

The simple modern templating engine

Twig is the simple templating engine, created specifically for web designers. It won’t slow down your app, and it automatically takes care of escaping and other tedious tasks.

Page components

Components are the building blocks for Pages. Just add the component to a Page to add a new functionality and configure it with a Inspector. An Inspector is the visual tool for managing component properties.

Extensible platform

Extend the platform with Plugins that seamlessly integrate with October’s back-end and front-end. Plugin classes are elementary, and you can describe the Plugin and register the features that you want in October.

Easy administrative interfaces

Effortlessly create back-end interfaces for your plugins. Back-end pages require minimal PHP coding and use simple configuration files.

Simple AJAX framework

The AJAX framework lets you efficiently bind the AJAX request to the form or a button. These requests can be handled by the components or by your code in a Page or Layout.

How To Install October CMS on Mac

First, you need to download the zip file from its documentation. You can find it on here.

There are some system requirements. I am listing here.

  1. PHP version 7.0 or higher
  2. PDO PHP Extension
  3. cURL PHP Extension
  4. OpenSSL PHP Extension
  5. Mbstring PHP Library
  6. ZipArchive PHP Library
  7. GD PHP Library

Now, after downloading that file, you need to place that zip folder inside your server root. If you are using localhost via MAMP or XAMPP, then your web root might be an htdocs folder. So you need to place that zip file inside that folder and now unzip them.

Next step, is to permit the folder and its subfolders.

Next step is to open the browser and navigate to this URL: http://localhost/install-master/install.php

My OctoberCMS folder’s name is install-master, and yours might be as well.

If you navigate to this URL, then you might see the below screen.

 

How To Install October CMS on Mac

Click agree and continue to the next step.

Now, you need to create a database inside the MySQL. So create one database inside phpmyadmin.

After that, navigate to the octobercms’ database configuration page and fill the details.

 

October CMS Tutorial With Example

After filling all the information, click the Administrator button.

Now, fill the administrator details.

 

OctoberCMS Example Tutorial

After clicking the continue button, you have three options.

 

October CMS From Scratch

For this demo, let us start with Start from scratch option.

Now, you can see that our installation process has begun. Finally, our installation has successful, and you can see that we got the two URLs — one for frontend and one for the backend.

 

OctoberCMS installation

Finally, How To Install October CMS on Mac tutorial is over. Thanks for taking.

The post How To Install October CMS on Mac appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/30/how-to-install-october-cms-on-mac/feed/ 1
How To Install Statamic | Laravel Based CMS https://appdividend.com/2018/11/27/how-to-install-statamic-laravel-based-cms/ https://appdividend.com/2018/11/27/how-to-install-statamic-laravel-based-cms/#comments Tue, 27 Nov 2018 14:07:58 +0000 http://localhost/wordpress/?p=2350 Statamic Guide

In this tutorial demo, we will see How To Install Statamic – The Laravel Based CMS on Mac. Statamic does not require the database .So it creates a faster, more productive way for you to build, manage, and version control beautifully creative, bespoke websites. Statamic is made on the top of Laravel, the most modern, robust, and secure […]

The post How To Install Statamic | Laravel Based CMS appeared first on AppDividend.

]]>
Statamic Guide

In this tutorial demo, we will see How To Install Statamic – The Laravel Based CMS on Mac. Statamic does not require the database .So it creates a faster, more productive way for you to build, manage, and version control beautifully creative, bespoke websites. Statamic is made on the top of Laravel, the most modern, robust, and secure PHP framework ever created. 

The Statamic includes most (if not all) of the features you would typically need to create an informative and blogging websites If you want to take your website to the next level quickly, cost-efficiently, and securely, then Statamic CMS is for you.

Instead of requiring a database you can neither touch nor version control, Statamic stores all of your content and configurations in files. Text files, Markdown files, YAML files, and so on. You can see them, touch them, edit them in any editor of your choosing, and even email them to a friend for editing. Combine these files with HTML, CSS, and our Antlers template language, your site comes alive with possibilities.

How To Install Statamic Development Version

Actual Statmic CMS is not free, and you need to buy the license to use on the production version. You can find more on this page. But, for development, they are allowing us to use the free version of the CMS. So for this tutorial, I am using the development version of the Statmic CMS. You can download the development version from this page. Provide your email address, and you can download the zip file containing the CMS.

Requirements of Statamic CMS

Statamic has the few server requirements. Statamic v2 is built on the top of Laravel, so as a rule of thumb — anywhere around Laravel 5.1 runs, Statamic runs.

Server Requirements

  • The web server: Apache, Nginx, or IIS
  • PHP >= 5.5.9
  • URL Rewriting must be enabled (mod_rewrite, try_files, etc.)

Required PHP Extensions

These should all be included in PHP 5.5.9+ by default, but in case you’re a tinkerer, you’re going to need these extensions:

#1: Install Statmic CMS

After downloading the zip file, you need to extract it to either your server root or in my case I am using Laravel Valet, so my root is the sites folder. So I will unzip the project inside that directory.

Now, we go inside that folder root and open the terminal and give the permission.

sudo chmod -R 777 statamic

Your project folder looks like this.

 

How To Install Statamic | Laravel Based CMS

Now, since my Laravel Valet is running, now I can access the website using the following URL.

http://statamic.test/

Since my project name is statamic, I can access it like above URL.

 

#2: Configure the .htaccess file

Now, our home page is running, but other pages will not work because we need to set up the URL rewrite.

So, let us do that using the following command. Please make sure, you are inside the statamic root folder which we have downloaded.

mv sample.htaccess .htaccess

Now, we have set up the rewrite, now we able to navigate any pages with the proper response.

#3: Configure the admin panel

Right now, we have just seen the frontend and not the backend. For that, first, we need to create a User. So type the following URL in the browser.

http://statamic.test/installer.php

You can see the page like this.

 

Statamic cms example tutorial

Please check, if your server is compatible with Statmic. Otherwise, please upgrade it and then come back here. Mine is compatible. So let us go to the next step.

#4: Continue to trial mode

We can continue with the trial mode. If you are on the production version, then you should have the license key.

 

Statamic trial demo

#5: Set the locales

By default there is en, but you can add as you wish and also turn to debug mode on.

 

Locales in Statamic

#6: Create a Statmic User

Create a statmic backend user. 

 

Create a Statamic User

Fill the details and you will be redirected to the dashboard.

 

Statamic Guide

Finally, we have successfully installed the Statmic CMS on Mac. How To Install Statamic tutorial is over. Thanks for taking this demo.

The post How To Install Statamic | Laravel Based CMS appeared first on AppDividend.

]]>
https://appdividend.com/2018/11/27/how-to-install-statamic-laravel-based-cms/feed/ 1
Laravel 5.7 Email Verification Tutorial Example https://appdividend.com/2018/09/11/laravel-5-7-email-verification-tutorial-example/ https://appdividend.com/2018/09/11/laravel-5-7-email-verification-tutorial-example/#comments Tue, 11 Sep 2018 19:41:32 +0000 http://localhost/wordpress/?p=1652 Laravel 5.7 Email Verification Example

Laravel 5.7 Email Verification Tutorial Example From Scratch is today’s leading topic. In this version, you need to configure the settings and write some minimal code to setup everything. Email verification is the must functionality in web apps, and laravel makes very easy. So let us do it then. PHP with Laravel for beginners – Become […]

The post Laravel 5.7 Email Verification Tutorial Example appeared first on AppDividend.

]]>
Laravel 5.7 Email Verification Example

Laravel 5.7 Email Verification Tutorial Example From Scratch is today’s leading topic. In this version, you need to configure the settings and write some minimal code to setup everything. Email verification is the must functionality in web apps, and laravel makes very easy. So let us do it then.

Laravel 5.7 Email Verification Tutorial Example

First, install the Laravel 5.7 using the following command.

#1: Install Laravel 5.7 and configure the database.

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

# or

laravel new emailVerify

 

Laravel 5.7 Email Verification Tutorial Example

Go inside the folder.

cd emailVerify

Fire up your favorite IDE or Editor.

code .

Create the MySQL database and write the credentials inside the .env file.

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

Okay, now migrate the tables by the following command.

php artisan migrate

Now, see the users table and you can there is one more field called email_verified_at.

 

Laravel 5.7 Email Verification

The email_verified_at column is there which is new in Laravel 5.7. So when the user registers and verifies the email, the timestamp will be recorded here. So based on that, we can differentiate that user has confirmed the email or not. For this kind of functionality, We have generally used the datatype boolean, but nowadays people are using a timestamp to accomplish this kind of goal.

#2: Laravel 5.7 Auth Scaffolding

Okay, now go to the terminal and type the following command.

php artisan make:auth

This command has generated one more view called verify.blade.php. It is new in Laravel 5.7 as the verification functionality is implemented in this version.

@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-header">{{ __('Verify Your Email Address') }}</div>

                <div class="card-body">
                    @if (session('resent'))
                        <div class="alert alert-success" role="alert">
                            {{ __('A fresh verification link has been sent to your email address.') }}
                        </div>
                    @endif

                    {{ __('Before proceeding, please check your email for a verification link.') }}
                    {{ __('If you did not receive the email') }}, <a href="{{ route('verification.resend') }}">{{ __('click here to request another') }}</a>.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

#3: Implement mustVerify interface in the User model.

In the User.php model, you can see one more contract added called  MustVerifyEmail. To use the email verification process, we need to implement this contract.

<?php

namespace App;

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

class User extends Authenticatable implements MustVerifyEmail
{
    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',
    ];
}

#4: Add Email Route Verification

Go to the routes >> web.php file and add the extra parameter inside Auth::routes().

Auth::routes(['verify' => true]);

This enables the new Verification controller with the route actions. You can see the new controller called VerificationController.php file already comes with Laravel 5.7.

Also, we need to protect the HomeController route, so let us do that via adding middleware.

   /** HomeController.php
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified']);
    }

#5: Setup email configuration

I am using mailtrap for this example. So log in to the https://mailtrap.io/signin.

Go to the demo inbox and copy the credentials and paste to your .env file.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

#6: Test the email verification functionality.

First, go to the browser and go to either http://localhost:8000/register or like me go to the http://emailverify.test/.register 

You will see the page like this.

 

Verify Email in Laravel

Now go the mailtrap, and you can see that verification mail has arrived.

 

Email Verification in Laravel 5.7

Also, see the database and analyze the users table.

 

Laravel 5.7 Auth Functionality

Here, the email_verified_at is null. Now, click the link that is arrived at your email and your email will be verified and you can see here the timestamp will be registered.

 

Email verified in Laravel

So, finally Laravel 5.7 Email Verification Tutorial Example is over. Thanks for taking.

The post Laravel 5.7 Email Verification Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/11/laravel-5-7-email-verification-tutorial-example/feed/ 8
Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch https://appdividend.com/2018/09/06/laravel-5-7-crud-example-tutorial/ https://appdividend.com/2018/09/06/laravel-5-7-crud-example-tutorial/#comments Thu, 06 Sep 2018 18:57:28 +0000 http://localhost/wordpress/?p=1608 Laravel 5.7 CRUD Operation Tutorial Example

Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch is today’s leading topic. Laravel 5.7 has some new cool features as well as several other enhancement and bug fixes. In previous Laracon event, Taylor Otwell announced some of the notable changes which are the following. PHP with Laravel for beginners – Become a Master in Laravel Resources Directory Changes. Callable […]

The post Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch appeared first on AppDividend.

]]>
Laravel 5.7 CRUD Operation Tutorial Example

Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch is today’s leading topic. Laravel 5.7 has some new cool features as well as several other enhancement and bug fixes. In previous Laracon event, Taylor Otwell announced some of the notable changes which are the following.

  1. Resources Directory Changes.
  2. Callable Action URLs.
  3. Laravel Dump Server.
  4. Improved Error Messages For Dynamic Calls.

Now in this tutorial, first we will install the Laravel 5.7 and then build a CRUD application.

Laravel 5.7 CRUD Example Tutorial

First, let us install Laravel 5.7 using the following command. We will use Composer Create-Project to generate laravel 5.7 projects.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Start your free trial

#1: Install Laravel 5.7

Type the following command. Make sure you have installed composer in your machine.

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

 

Laravel 5.7 CRUD Example Tutorial

Okay, now go inside the folder and install the npm packages using the following command. The requirement for the below command is that node.js is installed on your machine. So, if you have not installed, then please install it using its official site.

npm install

#2: Configure 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.

Now, After creating the database, we need to open the .env file inside Laravel stocks project and add the database credentials. I have typed my credentials; please enter yours otherwise it won’t connect.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel57
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

 

Laravel 5.7 Tutorial

#3: Create a model and migration file.

Go to the terminal and type the following command to generate the model and migration file.

php artisan make:model Share -m

It will create the model and migration file. Now, we will write the schema inside <timestamp>create_shares_table.php file.

   /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('shares', function (Blueprint $table) {
            $table->increments('id');
            $table->string('share_name');
            $table->integer('share_price');
            $table->integer('share_qty');
            $table->timestamps();
        });
    }

Okay now migrate the table using the following command.

php artisan migrate

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Share extends Model
{
  protected $fillable = [
    'share_name',
    'share_price',
    'share_qty'
  ];
}

#4: Create routes and controller

First, create the ShareController using the following command.

php artisan make:controller ShareController --resource

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

<?php

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

Route::resource('shares', 'ShareController');

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.7 Example

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ShareController 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)
    {
        //
    }
}

#5: Create the views

Inside resources >> views folder, create one folder called shares.

Inside that folder, create the following three files.

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

But inside 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.

<!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.7 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 four by adding the app.css.

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

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Share
  </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('shares.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Share Name:</label>
              <input type="text" class="form-control" name="share_name"/>
          </div>
          <div class="form-group">
              <label for="price">Share Price :</label>
              <input type="text" class="form-control" name="share_price"/>
          </div>
          <div class="form-group">
              <label for="quantity">Share Quantity:</label>
              <input type="text" class="form-control" name="share_qty"/>
          </div>
          <button type="submit" class="btn btn-primary">Add</button>
      </form>
  </div>
</div>
@endsection

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

// ShareController.php

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

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

php artisan serve

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

You can see something like this.

 

Laravel 5.7 Demo For Beginners

#6: Save the data

Now, we need to code the store function to save the data in the database. First, include the Share.php model inside ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

class ShareController 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()
    {
        return view('shares.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

    /**
     * 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)
    {
        //
    }
}

If the validation fails, then it will throw an error, and we will display inside the create.blade.php file.

If all the values are good and pass the validation, then it will save the values in the database.

 

Laravel 5.7 CRUD

#7: Display the data.

Okay, now open the file called index.blade.php file and add the following code.

@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>Stock Name</td>
          <td>Stock Price</td>
          <td>Stock Quantity</td>
          <td colspan="2">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($shares as $share)
        <tr>
            <td>{{$share->id}}</td>
            <td>{{$share->share_name}}</td>
            <td>{{$share->share_price}}</td>
            <td>{{$share->share_qty}}</td>
            <td><a href="{{ route('shares.edit',$share->id)}}" class="btn btn-primary">Edit</a></td>
            <td>
                <form action="{{ route('shares.destroy', $share->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

Next thing is we need to code the index() function inside ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

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

        return view('shares.index', compact('shares'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

    /**
     * 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)
    {
        //
    }
}

#8: Edit and Update Data

First, we need to code the edit() function inside  ShareController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Share;

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

        return view('shares.index', compact('shares'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);
      $share = new Share([
        'share_name' => $request->get('share_name'),
        'share_price'=> $request->get('share_price'),
        'share_qty'=> $request->get('share_qty')
      ]);
      $share->save();
      return redirect('/shares')->with('success', 'Stock has been added');
    }

    /**
     * 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)
    {
        $share = Share::find($id);

        return view('shares.edit', compact('share'));
    }

    /**
     * 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)
    {
        //
    }
}

Now, add the following lines of code inside the edit.blade.php file.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Edit Share
  </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('shares.update', $share->id) }}">
        @method('PATCH')
        @csrf
        <div class="form-group">
          <label for="name">Share Name:</label>
          <input type="text" class="form-control" name="share_name" value={{ $share->share_name }} />
        </div>
        <div class="form-group">
          <label for="price">Share Price :</label>
          <input type="text" class="form-control" name="share_price" value={{ $share->share_price }} />
        </div>
        <div class="form-group">
          <label for="quantity">Share Quantity:</label>
          <input type="text" class="form-control" name="share_qty" value={{ $share->share_qty }} />
        </div>
        <button type="submit" class="btn btn-primary">Update</button>
      </form>
  </div>
</div>
@endsection

Finally, code the update function inside ShareController.php file.

public function update(Request $request, $id)
{
      $request->validate([
        'share_name'=>'required',
        'share_price'=> 'required|integer',
        'share_qty' => 'required|integer'
      ]);

      $share = Share::find($id);
      $share->share_name = $request->get('share_name');
      $share->share_price = $request->get('share_price');
      $share->share_qty = $request->get('share_qty');
      $share->save();

      return redirect('/shares')->with('success', 'Stock has been updated');
}

So, now you can update the existing values.

#9: Delete the data

Just code the delete function inside ShareController.php file.

public function destroy($id)
{
     $share = Share::find($id);
     $share->delete();

     return redirect('/shares')->with('success', 'Stock has been deleted Successfully');
}

Finally, Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch is over. I have put the code in the Github Repo. So check out as well.

Github Code

The post Laravel 5.7 CRUD Example Tutorial For Beginners From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/09/06/laravel-5-7-crud-example-tutorial/feed/ 56
Laravel 5.7 Features and Updates | What Is New https://appdividend.com/2018/08/22/laravel-5-7-features-and-updates-what-is-new/ https://appdividend.com/2018/08/22/laravel-5-7-features-and-updates-what-is-new/#comments Wed, 22 Aug 2018 10:07:45 +0000 http://localhost/wordpress/?p=1520 Laravel 5.7 Resources Directory Changes

In this post, we will talk about Laravel 5.7 Features and Updates | What Is New. Laravel 5.7 has some new cool features as well as several other enhancement and bug fixes. We will discuss some of the noticeable changes and some of the new additions to the Laravel 5.7 family. If you want to master in […]

The post Laravel 5.7 Features and Updates | What Is New appeared first on AppDividend.

]]>
Laravel 5.7 Resources Directory Changes

In this post, we will talk about Laravel 5.7 Features and Updates | What Is New. Laravel 5.7 has some new cool features as well as several other enhancement and bug fixes. We will discuss some of the noticeable changes and some of the new additions to the Laravel 5.7 family.

If you want to master in Laravel then check out this course. It has everything you want to know.
PHP with Laravel for beginners – Become a Master in Laravel

Laravel 5.7 Features and Updates

In previous Laracon event, Taylor Otwell announced some of the changes which are the following.

  1. Resources Directory Changes.
  2. Callable Action URLs.
  3. Laravel Dump Server.
  4. Improved Error Messages For Dynamic Calls.

Install Laravel 5.7 From Develop Branch

You can install the latest Laravel by typing the following command.

composer create-project laravel/laravel test dev-develop

 

Laravel 5.7 Features and Updates | What Is New

#Laravel 5.7 Resources Directory Changes

If you open the test project in a code editor, you can see the directory structure changes. Resources directory will be flattened instead of having an assets folder.

 

Laravel 5.7 Resources Directory Changes

To update from Laravel 5.6 to 5.7, You could even make a move now in your Laravel 5.6 assets ahead of this change. First, you need to update your Laravel Mix configuration.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program
let mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

Then you can move the directories and clean up with the following.

mv resources/assets/* resources
rm -Rf resources/assets/

#Laravel 5.7 Callable Action URLs

A new callable-like syntax for action URLs is coming to Laravel 5.7. You might also hear this feature called “tuple notation” or a “callable array syntax” for URL generation actions.

Here’s how it works starting in 5.7:

<?php

$url = action([UserController::class, 'index']);

As of Laravel 5.6 the action helper only supports the following style that you’re probably already familiar with:

<?php

$url = action('UserController@profile', ['id' => 1]);

The benefit of the new callable array syntax format is that you can able to navigate to directly to the controller file if you use a text editor like VSCode or Sublime or Atom or IDE like phpStorm that supports code navigation.

#Laravel Dump Server

Laravel Dump Server would come packaged with Laravel 5.7Dump Server will be the development dependency in laravel/laravel composer file. You’ll get this command out-of-the-box that allows you to dump data to the console or an HTML file instead of to the browser.

php artisan dump-server

 

Laravel Dump Server

#Laravel 5.7 Improved Error Messages for Dynamic Calls

Laravel 5.7 makes it easier to track down error messages caused by dynamic calls to Eloquent models. You’ll get a more clear picture of the error caused by a missing method instead of a possibly confusing error on the underlying object.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

#Laravel 5.7 Email Verification

Laravel 5.7 introduces optional email verification to the authentication scaffolding included with the framework. To accommodate this feature, an email_verified_at timestamp column has been added to the default users table migration that is included with the structure. To prompt newly registered users to verify their email, the User model should be marked with the MustVerifyEmail interface:

<?php

namespace App;

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

class User extends Authenticatable implements MustVerifyEmail
{
    // ...
}

#Guest User Gates / Policies

In previous versions of Laravel, authorization gates and policies automatically returned falsefor unauthenticated visitors to your application. However, you may now allow guests to pass through authorization checks by declaring an “optional” type-hint or supplying a null default value for the user argument definition:

Gate::define('update-post', function (?User $user, Post $post) {
    // ...
});

#Paginator Links

Laravel 5.7 allows you to control how many additional links are displayed on each side of the paginator’s URL “window.” By default, three links are displayed on each side of the primary paginator links. However, you may control this number using the onEachSide method:

{{ $paginator->onEachSide(5)->links() }}

#Filesystem Read / Write Streams

Laravel’s Flysystem integration now offers readStream and writeStream methods:

Storage::disk('s3')->writeStream(
    'remote-file.zip',
    Storage::disk('local')->readStream('local-file.zip')
);

#Laravel Nova

Laravel Nova is not a feature of Laravel. It is a different package that is created by Taylor Otwell. 

Laravel Nova is a beautiful, best-in-class administration dashboard for Laravel applications. Of course, the primary feature of Nova is the ability to administer your underlying database records using Eloquent. Additionally, Nova offers support for filters, lenses, actions, queued actions, metrics, authorization, custom tools, custom cards, custom fields, and more.

To learn more about Laravel Nova, check out the Nova website.

So these are packages and Laravel 5.7 Features and Updates

The post Laravel 5.7 Features and Updates | What Is New appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/22/laravel-5-7-features-and-updates-what-is-new/feed/ 5
Laravel File Upload Example Tutorial From Scratch https://appdividend.com/2018/08/15/laravel-file-upload-example/ https://appdividend.com/2018/08/15/laravel-file-upload-example/#comments Wed, 15 Aug 2018 06:25:55 +0000 http://localhost/wordpress/?p=1477 Laravel 5.6 File Upload Tutorial With Example From Scratch

Laravel File Upload Example is today’s leading topic. We use Laravel 5.6 for this tutorial and Bootstrap CSS Framework for frontend Design. First, we use Dropzone library to upload files into the Server. So basically it is a Laravel 5.6 Dropzone File Upload Tutorial. If you want to master in Laravel then check out this course. It has everything you […]

The post Laravel File Upload Example Tutorial From Scratch appeared first on AppDividend.

]]>
Laravel 5.6 File Upload Tutorial With Example From Scratch

Laravel File Upload Example is today’s leading topic. We use Laravel 5.6 for this tutorial and Bootstrap CSS Framework for frontend Design. First, we use Dropzone library to upload files into the Server. So basically it is a Laravel 5.6 Dropzone File Upload Tutorial.

If you want to master in Laravel then check out this course. It has everything you want to know.
PHP with Laravel for beginners – Become a Master in Laravel

Laravel File Upload Example

Install Laravel using the following command. I am using Laravel Valet for this project.

#1: Install Laravel 5.6

Type the following command.

laravel new fileupload

Go into the project folder and install the frontend dependencies.

npm install

Setup the Database inside the .env file.

Next step is to create an auth using the following command.

php artisan make:auth

Now, migrate the database using the following command.

php artisan migrate

#2: Create Files table.

Okay, now we need to create a File model and migrations using the following command.

php artisan make:model File -m

Define the schema inside the newly created migration file.

// create_files_table

<?php

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

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('title');
            $table->text('overview');
            $table->decimal('price', 6, 2);
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
}
Want to learn to code, gain a new skill and get a new job. Check out this amazing program

Now, migrate using the following command.

php artisan migrate

Next step is to build a relationship between User and File models.

Inside File.php, write the following code.

<?php

// File.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class File extends Model
{
    use SoftDeletes;

    protected $fillable = [
      'title',
      'overview',
      'price'
    ];

    public function user()
    {
      return $this->belongsTo(User::class);
    }
}

So, here we have stated that every file belongs to a particular User.

Now, define the Relationship inside User.php model.

<?php

// User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

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',
    ];

    public function files()
    {
      return $this->hasMany(File::class);
    }
}

#3: Create a View and Route for uploading files.

Create a FileController using the following command.

php artisan make:controller FileController

Inside home.blade.php file, write the following code inside it.

@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-header">File Upload</div>
                <div class="card-body">
                <form method="POST" action="{{ route('file.upload') }}" aria-label="{{ __('Upload') }}">
                        @csrf
                        <div class="form-group row">
                            <label for="title" class="col-sm-4 col-form-label text-md-right">{{ __('Title') }}</label>
                            <div class="col-md-6">
                                <input id="title" type="text" class="form-control{{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" value="{{ old('title') }}" required autofocus />
                                @if ($errors->has('title'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('title') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="overview" class="col-sm-4 col-form-label text-md-right">{{ __('Overview') }}</label>
                            <div class="col-md-6">
                                <textarea id="overview" cols="10" rows="10" class="form-control{{ $errors->has('overview') ? ' is-invalid' : '' }}" name="overview" value="{{ old('overview') }}" required autofocus></textarea>
                                @if ($errors->has('overview'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('overview') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="price" class="col-md-4 col-form-label text-md-right">{{ __('Price') }}</label>
                            <div class="col-md-6">
                                <input id="price" type="text" class="form-control{{ $errors->has('price') ? ' is-invalid' : '' }}" name="price" required>
                                @if ($errors->has('price'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('price') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Upload') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Also, you need to define the Post route inside routes >> web.php file.

<?php

// web.php

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

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::post('file/upload', 'FileController@store')->name('file.upload');

Now, save the file and register the user and you can see this page.

Laravel File Upload Example

 

Okay, now from the form you can see that we have not used any file form field yet. We will do it in a minute, but this is our primary form setup.

#4: Storing the form data.

Now, we need to write the store function to save the data in the database.

<?php

// FileController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileController extends Controller
{
    public function store(Request $request)
    {
       $request->validate([
        'title' => 'required:max:255',
        'overview' => 'required',
        'price' => 'required|numeric'
      ]);

      auth()->user()->files()->create([
        'title' => $request->get('title'),
        'overview' => $request->get('overview'),
        'price' => $request->get('price')
      ]);

      return back()->with('message', 'Your file is submitted Successfully');
    }
}

We have also included the validation for our form fields.

Also, we need to update our view to see the flash message.

// home.blade.php 

@if(session()->get('message'))
    <div class="alert alert-success">
       {{ session()->get('message') }}
    </div>
@endif

#5: Setup File Upload Relationship.

Now, we will create another model and migration for the uploading files.

Type the following command to generate model and migration.

php artisan make:model Upload -m

Write the following schema inside <timestamp>create_uploads_table.php file.

// create_uploads_table.php

public function up()
{
        Schema::create('uploads', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('filename');
            $table->softDeletes();
            $table->timestamps();

            $table->foreign('user_id')
                  ->references('id')
                  ->on('users')
                  ->onDelete('cascade');
        });
}

Migrate the database using the following command.

php artisan migrate

Okay, now we need to set up the relationships.

Inside Upload.php file write the following code.

<?php

// Upload.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Upload extends Model
{

  protected $fillable = [
    'filename'
  ];

    public function user()
    {
      return $this->belongsTo(User::class);
    }
}

Here, Upload is belongsTo File and User.

So, now write the following relationship methods inside the User.php model.

// User.php

public function files()
{
   return $this->hasMany(File::class);
}

public function uploads()
{
   return $this->hasMany(Upload::class);
}

Finally, write the following relationships inside the File.php model.

// File.php

public function user()
{
   return $this->belongsTo(User::class);
}

#6: Setup the Dropzone.

Install the Dropzone library using the following command.

npm install dropzone --save

Now, include this library inside resources >> assets >> js >> bootstrap.js file. We need to add the code inside that file.

// bootstrap.js

/**
 * Dropzone
 */

 window.Dropzone = require('dropzone');
 Dropzone.autoDiscover = false;

Okay, now we need to import the Dropzone css files. So inside resources >> assets >> sass >> app.scss file, add the following code.

// app.scss

// Fonts
@import url('https://fonts.googleapis.com/css?family=Nunito');

// Variables
@import 'variables';

// Bootstrap
@import '~bootstrap/scss/bootstrap';

// Dropzone
@import '~dropzone/dist/min/dropzone.min.css';

.dropzone {
  margin-bottom: 20px;
  min-height: auto;
}

Now, compile the file using the following command.

npm run dev

Okay, now we need to use the Dropzone library 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('message'))
            <div class="alert alert-success">
              {{ session()->get('message') }}
            </div>
            @endif
            <div class="card">
                <div class="card-header">File Upload</div>
                <div class="card-body">
                <form method="POST" action="{{ route('file.upload') }}" aria-label="{{ __('Upload') }}">
                      @csrf
                      <div class="form-group row ">
                        <label for="title" class="col-sm-4 col-form-label text-md-right">{{ __('File Upload') }}</label>
                        <div class="col-md-6">
                          <div id="file" class="dropzone"></div>
                        </div>    
                      </div>
                        <div class="form-group row">
                            <label for="title" class="col-sm-4 col-form-label text-md-right">{{ __('Title') }}</label>
                            <div class="col-md-6">
                                <input id="title" type="text" class="form-control{{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" value="{{ old('title') }}" required autofocus />
                                @if ($errors->has('title'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('title') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="overview" class="col-sm-4 col-form-label text-md-right">{{ __('Overview') }}</label>
                            <div class="col-md-6">
                                <textarea id="overview" cols="10" rows="10" class="form-control{{ $errors->has('overview') ? ' is-invalid' : '' }}" name="overview" value="{{ old('overview') }}" required autofocus></textarea>
                                @if ($errors->has('overview'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('overview') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="price" class="col-md-4 col-form-label text-md-right">{{ __('Price') }}</label>
                            <div class="col-md-6">
                                <input id="price" type="text" class="form-control{{ $errors->has('price') ? ' is-invalid' : '' }}" name="price" required>
                                @if ($errors->has('price'))
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $errors->first('price') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Upload') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
  <script>
    var drop = new Dropzone('#file', {
      url: "{{ route('upload') }}"
    });
  </script>
@endsection

Also, define the POST route to upload a file.

// web.php

Route::post('upload', 'FileController@upload')->name('upload');

Create an upload function inside FileController.php file.

// FileController.php

public function upload()
{
   return 'x';
}

Save the file and go to the http://fileupload.test/home.

Laravel Dropzone File Upload Example

 

#7: Handling File Upload Process.

First thing, we need to do is that add the headers while sending a POST request to the server.

// home.blade.php

@section('scripts')
  <script>
    var drop = new Dropzone('#file', {
      createImageThumbnails: false,
      addRemoveLinks: true,
      url: "{{ route('upload') }}",
      headers: {
        'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content
      }
    });
  </script>
@endsection

Now, final code for the FileController.php file looks like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Upload;

class FileController extends Controller
{
    public function store(Request $request)
    {
       $request->validate([
        'title' => 'required:max:255',
        'overview' => 'required',
        'price' => 'required|numeric'
      ]);

      auth()->user()->files()->create([
        'title' => $request->get('title'),
        'overview' => $request->get('overview'),
        'price' => $request->get('price')
      ]);

      return back()->with('message', 'Your file is submitted Successfully');
    }

    public function upload(Request $request)
    {
      $uploadedFile = $request->file('file');
      $filename = time().$uploadedFile->getClientOriginalName();

      Storage::disk('local')->putFileAs(
        'files/'.$filename,
        $uploadedFile,
        $filename
      );

      $upload = new Upload;
      $upload->filename = $filename;

      $upload->user()->associate(auth()->user());

      $upload->save();

      return response()->json([
        'id' => $upload->id
      ]);
    }
}

Laravel 5.6 File Upload Example Tutorial

 

Now, you can see the uploaded file inside Storage >> app >> files folder.

Finally, Laravel File Upload Example Tutorial is over. Thanks for taking.

 

The post Laravel File Upload Example Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/15/laravel-file-upload-example/feed/ 4
Laravel Elasticsearch Tutorial Example From Scratch https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/ https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/#comments Sat, 30 Jun 2018 23:25:57 +0000 http://localhost/wordpress/?p=1222 Elasticsearch using Elasticquent in Laravel

Laravel Elasticsearch Tutorial Example From Scratch is the today’s leading topic. For this example, we use the composer package called Elasticquent. It is called Elasticsearch for Eloquent Laravel Models. Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the […]

The post Laravel Elasticsearch Tutorial Example From Scratch appeared first on AppDividend.

]]>
Elasticsearch using Elasticquent in Laravel

Laravel Elasticsearch Tutorial Example From Scratch is the today’s leading topic. For this example, we use the composer package called ElasticquentIt is called Elasticsearch for Eloquent Laravel Models. Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the model. The Elasticquent allows you take an Eloquent model and easily index and search its contents in Elasticsearch. Okay, let us start the Laravel Elasticsearch Tutorial Example.

If you want to master in Laravel then check out this course. It has everything you want to know.
PHP with Laravel for beginners – Become a Master in Laravel

Laravel Elasticsearch Tutorial Example

We begin this example by install Elasticsearch on the mac and then set up the laravel development environment.

#Step 1: Install Elasticsearch on Mac.

If you have not previously installed Elasticsearch on the mac then you need this step otherwise you can skip this step.  Type the following cmd in your terminal to install Elasticsearch via homebrew.

brew install elasticsearch

It will install it and now start the services using the following command.

brew services start elasticsearch

#Step 2: Setup Laravel and Elasticsearch env.

Install Laravel 5.6 by the following command.

laravel new elasticlaravel

Go into the project folder.

cd elasticlaravel

Open the project in your editor.

code .

Configure the database inside the .env file.

Add the following line inside the composer.json file. We are installing Elasticquent package.

"require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.6.*",
        "laravel/tinker": "^1.0",
        "elasticquent/elasticquent": "dev-master"
    },

Type the following command to install the elasticquent package.

composer update

 

Laravel Elasticsearch Tutorial Example

Once you’ve run a composer update command, you need to register Laravel service provider, in your config/app.php file.

// config/app.php

'providers' => [
    ...
    Elasticquent\ElasticquentServiceProvider::class,
],

We also provide a facade for an elasticsearch-php client (which has connected using our settings), add following to your config/app.php if you need so.

// config/app.php

'aliases' => [
    ...
    'Es' => Elasticquent\ElasticquentElasticsearchFacade::class,
],

#Elasticsearch Configuration

Type the following Artisan command to publish the configuration file into your config directory for Laravel 5.6.

php artisan vendor:publish --provider="Elasticquent\ElasticquentServiceProvider"

Now go to the config file at app >> config >> elastiquent.php

We need to add the index name for our application. So let us change from default to articles.

<?php

// elastiquent.php

return array(

    /*
    |--------------------------------------------------------------------------
    | Custom Elasticsearch Client Configuration
    |--------------------------------------------------------------------------
    |
    | This array will be passed to the Elasticsearch client.
    | See configuration options here:
    |
    | http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_configuration.html
    */

    'config' => [
        'hosts'     => ['localhost:9200'],
        'retries'   => 1,
    ],

    /*
    |--------------------------------------------------------------------------
    | Default Index Name
    |--------------------------------------------------------------------------
    |
    | This is the index name that Elasticquent will use for all
    | Elasticquent models.
    */

    'default_index' => 'articles',

);

#Step 3: Create an Article model and migration.

We will search the articles using elasticsearch. To create a model and migration using the following command.

php artisan make:model Article -m

In your <DATETIME>_create_articles_table.php file add the schema code.

// create_articles_table.php

public function up()
{
   Schema::create('articles', function (Blueprint $table) {
       $table->increments('id');
       $table->string('title');
       $table->text('body');
       $table->string('tags');
       $table->timestamps();
   });
}

Migrate the table using the following command.

php artisan migrate

#Step 4: Create the dummy data.

Create an ArticleTableSeeder using the following command.

php artisan make:seeder ArticleTableSeeder

For generating the fake data, we use Faker library. However, before that, we need to add the protected $fillable fields inside Article.php file to prevent the mass assignment exception.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program
// Article.php

class Article extends Model
{
    protected $fillable = ['title', 'body', 'tags'];
}

Now, add the following code inside ArticleTableSeeder.php file.

<?php

// ArticleTableSeeder.php

use Illuminate\Database\Seeder;
use App\Article;

class ArticleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();

        for($i=0; $i<50; $i++) {
          Article::create([
            'title' => $faker->sentence(3),
            'body' => $faker->paragraph(6),
            'tags' => join(',', $faker->words(4))
          ]);
        }
    }
}

Add the ArticleTableSeeder class inside DatabaseSeeder.php file which is located in the same directory.

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

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

Okay, now run the seeder and create the fake data using the following command.

php artisan db:seed

 

Elasticsearch in Laravel

#Step 5: Set up Elastiquent inside Article model.

Write the following code inside Article.php file.

<?php

// Article.php

namespace App;
use Elasticquent\ElasticquentTrait;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use ElasticquentTrait;

    protected $fillable = ['title', 'body', 'tags'];

    protected $mappingProperties = array(
        'title' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
        'body' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
        'tags' => [
          'type' => 'text',
          "analyzer" => "standard",
        ],
      );
}

Here, we add our mapping configuration for ElasticSearch. The database table has three main fields. So we need to assign the type and analyzer which in our case is standard. Remember, our index name is articles. The mappingProperties array is the fields that need to be indexed with the proper type to search and get the perfect results. Each mapping has a kind and an analyzer. Type’s can be various data types including strings, numbers, and dates. For now, we will stick to the text type but be aware that different types allow you to take advantage of different things. You can find more datatype here at the original elasticsearch docs.

Okay, now we need to index the database. So inside web.php file, write the following code. Remember, I have written the following code inside web.php file but in a real-time scenario, you need to write this inside controller or any other logical part of your app except web.php file.

#Indexing Documents

To index all the entries in an Eloquent model, use addAllToIndex:

    Article::addAllToIndex();

You can also index a collection of models:

    $articles = Article::where('id', '<', 200)->get();
    $articles->addToIndex();

You can index individual entries as well:

    $articles = Article::find($id);
    $articles->addToIndex();

You can also reindex an entire model:

     Article::reindex()

Now, we index the whole model so that we can write the indexing code inside root route.

<?php

// web.php

use App\Article;

Route::get('/', function () {
    Article::createIndex($shards = null, $replicas = null);

    Article::putMapping($ignoreConflicts = true);

    Article::addAllToIndex();

    return view('welcome');
});

Here, we have created the index. The name of the index is already defined inside config >> elastiquent.php file.

Then we have put the mapping, which is defined in the Article.php model and finally adds that to the indexing.

Go to the browser and hit this URL: http://elasticlaravel.test/

You will get the welcome page, but our data is entirely indexed and we can verify that by sending the following request using cURL. We can also use the postman for that, but I am sending the request via terminal.

curl 'localhost:9200/articles/_mapping?pretty'

 

Elastic search api for laravel with example

We can do a basic search using the following command.

curl 'localhost:9200/articles/articles/_search?q=title:Sed&pretty'

Here, our search term for the title is Sed. So it will fetch the records that have Sed term. We can see the prettify results inside a terminal.

Laravel Elasticsearch query example

 

#Step 6: Search using Laravel eloquent methods.

Okay so till now, we have used cURL for the searching the data. Now, we will use Elastiquent method to search the data. So let us create another route inside the web.php file and add the following code in it.

<?php

// Article.php

use App\Article;

Route::get('/', function () {
    Article::createIndex($shards = null, $replicas = null);

    Article::putMapping($ignoreConflicts = true);

    Article::addAllToIndex();

    return view('welcome');
});

Route::get('/search', function() {

    $articles = Article::searchByQuery(['match' => ['title' => 'Sed']]);

    return $articles;
});

I have passed the ‘Sed’ hardcoded, but in a real-time application, it will be our search term which is typed inside the search box. Now, switch to this URL: http://elasticlaravel.test/search. You can see the JSON response like this.

Search using elasticsearch in Laravel

 

Of course, you might be getting different data because it is randomly generated data. So first check the database and pick the term and then pass to the search engine and it will return something like this. So we have successfully indexed the data and fetched the data from the elasticsearch engine.

In this example, we have searched for the title, you can go for body and tags as well.

$articles = Article::searchByQuery(['match' => ['body' => 'eligendi']]);
    
return $articles;

And you can do the same for the tags as well.

#Search collections

We can get the total hits to count using the following code.

$articles = Article::searchByQuery(['match' => ['title' => 'Heleium']]);
    
 return $articles->totalHits();

Access the shards array:

 $articles->shards();

Access the max score:

 $articles->maxScore();

Access the timed out boolean property:

 $articles->timedOut();

Access the took property:

  $articles->took();

Access search aggregations – See Aggregations for details:

  $articles->getAggregations();

#Chunking results from Elastiquent.

To get the results in chunks, you can use the chunk() function.

$articles = Article::searchByQuery(['match' => ['title' => 'Similique']]);
    
return $articles->chunk(2);

Finally, Laravel Elasticsearch Tutorial Example is over. Thanks for taking.

The post Laravel Elasticsearch Tutorial Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/feed/ 8
How To Create Comment Nesting In Laravel From Scratch https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/ https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/#comments Wed, 20 Jun 2018 14:33:04 +0000 http://localhost/wordpress/?p=1115 How to use nesting in laravel

How To Create Comment Nesting In Laravel From Scratch is the today’s main topic. In any topic specific forum, there is always a structure, where you need to reply to someone’s comment and then somebody reply in their comment and so on. So comment nesting is very useful in any web application, which exposes public interest. […]

The post How To Create Comment Nesting In Laravel From Scratch appeared first on AppDividend.

]]>
How to use nesting in laravel

How To Create Comment Nesting In Laravel From Scratch is the today’s main topic. In any topic specific forum, there is always a structure, where you need to reply to someone’s comment and then somebody reply in their comment and so on. So comment nesting is very useful in any web application, which exposes public interest. In this tutorial, we will do it from scratch. We use Polymorphic relationship in this example.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Check out this amazing program

Create Comment Nesting In Laravel From Scratch

As always, install Laravel using the following command. I am using Laravel Valet.

Step 1: Install and configure Laravel.

laravel new comments

# or

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

Go to the project.

cd comments

Open the project in your editor.

code .

Configure the MySQL database in the .env file.

Create an auth using the following command.

php artisan make:auth

Now migrate the database using the following command.

php artisan migrate

Step 2: Create a model and migration.

Create a Post model and migration using the following command.

php artisan make:model Post -m

Define the schema in the post migration file.

// create_posts_table

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

Also, we need to create Comment model and migration, so create by using the following command.

php artisan make:model Comment -m

Okay, now we will use the Polymorphic relationship between the models. So we need to define the schema that way.

// create_comments_table

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
       $table->increments('id');
       $table->integer('user_id')->unsigned();
       $table->integer('parent_id')->unsigned();
       $table->text('body');
       $table->integer('commentable_id')->unsigned();
       $table->string('commentable_type');
       $table->timestamps();
    });
}

Now, migrate the database using the following cmd.

php artisan migrate

 

How To Create Comment Nesting In Laravel From Scratch

Step 3: Define Polymorphic Relationships.

Now, we need to define the Polymorphic relationships between the models. So write the following code inside app >> Post.php file. 

<?php

// Post.php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
    }
}

Here, we have written all the comments, whose parent_id is null. The reason is that we need to display the parent level comment and also save the parent level comment. That is why. We need to differentiate between the Comment and its replies.

Post also belongs To a User. So we can define that relationship as well.

<?php

// Post.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable')->whereNull('parent_id');
    }
}

Define the Comment relationship with the Post. Write the following code inside Comment.php file.

<?php

// Comment.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Step 3: Define the views, controller, and routes.

Create a PostController.php file using the following command.

php artisan make:controller PostController

Next step is to define the route for the view and store the post in the database. Write the following code inside routes >> web.php file.

<?php

// web.php

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

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

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

Write the following code inside PostController.php file.

<?php

// PostController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{

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

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

    public function store(Request $request)
    {
        // store code
    }
}

Now, first, we need to create a form for creating the post. So create a blade file inside resources >> views folder called post.blade.php. Write the following code inside a post.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-header">Create Post</div>
                <div class="card-body">
                    <form method="post" action="{{ route('post.store') }}">
                        <div class="form-group">
                            @csrf
                            <label class="label">Post Title: </label>
                            <input type="text" name="title" class="form-control" required/>
                        </div>
                        <div class="form-group">
                            <label class="label">Post Body: </label>
                            <textarea name="body" rows="10" cols="30" class="form-control" required></textarea>
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-success" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Okay, now go to the resources >> views >> layouts >> app.blade.php file and add a link to create a post.

We need to add the link to the @else part of the navigation bar. So, if the user is successfully logged in then and then he/she can create a post otherwise, he or she could not create a post.

@else
     <li class="nav-item">
          <a class="nav-link" href="{{ route('post.create') }}">Create Post</a>
     </li>

Now, go to this link: http://comments.test/register and register a user. After logged in, you can see the Create Post in the navbar. Click that item, and you will redirect to this route: http://comments.test/post/create. You can see, our form is there with the title and body form fields.

Comment Nesting in Laravel 5.6

 

Step 4: Save and display the Post.

Okay, now we need to save the post in the database, so write the following code inside store function of PostController.php file.

<?php

// PostController.php

namespace App\Http\Controllers;
use App\Post;

use Illuminate\Http\Request;

class PostController extends Controller
{

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

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

    public function store(Request $request)
    {
        $post =  new Post;
        $post->title = $request->get('title');
        $post->body = $request->get('body');

        $post->save();

        return redirect('posts');

    }
}

After saving the post, we are redirecting to the posts list page. We need to define its route too. Add the following route inside a web.php file.

// web.php

Route::get('/posts', 'PostController@index')->name('posts');

Also, we need to define the index function inside PostController.php file.

// PostController.php

public function index()
{
    $posts = Post::all();

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

Create an index.blade.php file inside views folder. Write the following code inside an index.blade.php file.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <table class="table table-striped">
                <thead>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Action</th>
                </thead>
                <tbody>
                @foreach($posts as $post)
                <tr>
                    <td>{{ $post->id }}</td>
                    <td>{{ $post->title }}</td>
                    <td>
                        <a href="{{ route('post.show', $post->id) }}" class="btn btn-primary">Show Post</a>
                    </td>
                </tr>
                @endforeach
                </tbody>

            </table>
        </div>
    </div>
</div>
@endsection

Now, define the show route inside a web.php file. Add the following line of code inside a web.php file.

// web.php

Route::get('/post/show/{id}', 'PostController@show')->name('post.show');

Also, define the show() function inside PostController.php file.

// PostController.php

public function show($id)
{
    $post = Post::find($id);

    return view('show', compact('post'));
}

Create a show.blade.php file inside views folder and add the following code.

@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>{{ $post->title }}</p>
                    <p>
                        {{ $post->body }}
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Okay, now you can see the individual posts. Fine till now.

Next step is to display the comments on this post.

Laravel Polymorphic morphMany relationship tutorial

 

Step 5: Create a form to add a comment.

First, create a CommentController.php file using the following command.

php artisan make:controller CommentController

Now, we need to create a form inside a show.blade.php file that can add the comment in the particular post.

Write the following code inside a show.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><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So, we have added a form that can add the comment. Now, we need to define the route to store the comment.

// web.php

Route::post('/comment/store', 'CommentController@store')->name('comment.add');

Okay, now write the store() function and save the comment using the morphMany() relationship.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\Post;

class CommentController extends Controller
{
    public function store(Request $request)
    {
        $comment = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user());
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($comment);

        return back();
    }
}

Okay, now if all is well then, we can now add the comments. Remember, we have not till now display the comments. Just complete the save functionality, whose parent_id is null.

Laravel Nested Set Example

 

Step 6: Display the comment.

Now, as we have set up the relationship between a Comment and a Post, we can easily pluck out all the comments related to a particular post.

So, write the following code inside the show.blade.php file. I am writing the whole file to display the comments. Remember, this is the parent comments. We still need to create a reply button and then show all the replies.

<!-- show.blade.php -->

@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><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Display Comments</h4>
                    @foreach($post->comments as $comment)
                        <div class="display-comment">
                            <strong>{{ $comment->user->name }}</strong>
                            <p>{{ $comment->body }}</p>
                        </div>
                    @endforeach
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now, add the comment, and it will show us here in the same url.

Laravel Nesting Relationships

 

Step 7: Create a Reply form and save replies.

Now, we need to create a function called replies() inside Comment.php model.

<?php

// Comment.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

Here, in the replies function, we need to add a primary key as a parent_id because we need to fetch a reply based on a parent comment’s id.

Okay, now we need to write the display of all the comments and its replies code into the partial blade file.

The reason behind is that, we need to nest the comment replies and how much nesting is required depends upon the user interaction. So we can not predict the nesting levels.

To make more and more flexible, we need to create partials and then repeat that partial to display the nested comment replies.

First, create a partials folder inside resources >> views folder and inside partials folder, create one file called _comment_replies.blade.php.

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

<!-- _comment_replies.blade.php -->

 @foreach($comments as $comment)
    <div class="display-comment">
        <strong>{{ $comment->user->name }}</strong>
        <p>{{ $comment->body }}</p>
        <a href="" id="reply"></a>
        <form method="post" action="{{ route('reply.add') }}">
            @csrf
            <div class="form-group">
                <input type="text" name="comment_body" class="form-control" />
                <input type="hidden" name="post_id" value="{{ $post_id }}" />
                <input type="hidden" name="comment_id" value="{{ $comment->id }}" />
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-warning" value="Reply" />
            </div>
        </form>
        @include('partials._comment_replies', ['comments' => $comment->replies])
    </div>
@endforeach

Here, I have displayed all the replies with the text box. So it can do further nesting.

Now, this partial is expect to parameters.

  1. comments
  2. post_id.

So, when we include this partial inside show.blade.php file, we do need to pass these both of the parameters so that we can access here.

Also, we need to define the route to save the reply.

Add the following line of code inside routes >> web.php file.

// web.php

Route::post('/reply/store', 'CommentController@replyStore')->name('reply.add');

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

<?php

// web.php

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

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

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

Route::get('/posts', 'PostController@index')->name('posts');
Route::get('/post/show/{id}', 'PostController@show')->name('post.show');

Route::post('/comment/store', 'CommentController@store')->name('comment.add');
Route::post('/reply/store', 'CommentController@replyStore')->name('reply.add');


Also, define the replyStore() function inside CommentController.php file.

I am writing here the full code of the CommentController.php file.

<?php

// CommentController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Comment;
use App\Post;

class CommentController extends Controller
{
    public function store(Request $request)
    {
        $comment = new Comment;
        $comment->body = $request->get('comment_body');
        $comment->user()->associate($request->user());
        $post = Post::find($request->get('post_id'));
        $post->comments()->save($comment);

        return back();
    }

    public function replyStore(Request $request)
    {
        $reply = new Comment();
        $reply->body = $request->get('comment_body');
        $reply->user()->associate($request->user());
        $reply->parent_id = $request->get('comment_id');
        $post = Post::find($request->get('post_id'));

        $post->comments()->save($reply);

        return back();

    }
}

So, here almost both of the function store and replyStore function is same. We are storing parent comment and its replies in the same table. But, when we are saving a parent comment, the parent_id becomes null, and when we store any reply, then parent_id becomes its comment_id. So that is the difference.

Finally, our show.blade.php file looks like this.

<!-- show.blade.php -->

@extends('layouts.app')
<style>
    .display-comment .display-comment {
        margin-left: 40px
    }
</style>
@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                    <p><b>{{ $post->title }}</b></p>
                    <p>
                        {{ $post->body }}
                    </p>
                    <hr />
                    <h4>Display Comments</h4>
                    @include('partials._comment_replies', ['comments' => $post->comments, 'post_id' => $post->id])
                    <hr />
                    <h4>Add comment</h4>
                    <form method="post" action="{{ route('comment.add') }}">
                        @csrf
                        <div class="form-group">
                            <input type="text" name="comment_body" class="form-control" />
                            <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        </div>
                        <div class="form-group">
                            <input type="submit" class="btn btn-warning" value="Add Comment" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Here, I have defined the CSS to display proper nesting.

Also, include the partials and pass the both of the parameters.

  1. Post comments.
  2. Post id

We can add the parent comment from here but can add the replies from the partials.

I have added the parent comment, and its replies and our database table looks like this.

Laravel Nested Set Database

 

Also, our final output looks like below.

Laravel 5.6 Polymorphic Nested Relationship Example

 

Finally, Create Comment Nesting In Laravel Tutorial With Example is over.

I have put the Github Code of Create Comment Nesting In Laravel so that you can check that out as well.

Github Code

Fork Me On Github

Steps To Use Code

  1. Clone the repository.
  2. Install the dependencies
  3. Configure the database.
  4. Migrate the database using this command: php artisan migrate
  5. Go to the register page and add the one user.
  6. Create the post and comment and reply on the comment.

The post How To Create Comment Nesting In Laravel From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/06/20/create-comment-nesting-in-laravel/feed/ 19