Laravel 5.4 – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Mar 2019 08:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel 5.4 – AppDividend https://appdividend.com 32 32 Laravel 5 Validation Example From Scratch https://appdividend.com/2017/07/11/laravel-5-4-validation-example-from-scratch/ https://appdividend.com/2017/07/11/laravel-5-4-validation-example-from-scratch/#comments Tue, 11 Jul 2017 11:36:51 +0000 http://localhost/appdividend/?p=635 Laravel 5.4 validation example from scratch

Today, Laravel 5 validation example is our main topic and let’s discuss it with some examples. Laravel is the fastest growing PHP MVC Framework, which provides us fluent API to build our web application and so we have also an API about Validate our form requests. If you are new to Laravel 5.4 then check out […]

The post Laravel 5 Validation Example From Scratch appeared first on AppDividend.

]]>
Laravel 5.4 validation example from scratch

Today, Laravel 5 validation example is our main topic and let’s discuss it with some examples. Laravel is the fastest growing PHP MVC Framework, which provides us fluent API to build our web application and so we have also an API about Validate our form requests. If you are new to Laravel 5.4 then check out my this article Laravel 5.4 CRUD example from scratch

Laravel 5 Validation Example From Scratch

We will start our Laravel Validation Tutorial by installing the Laravel project.

Step 1: Create a project of Laravel 5 Validation

Install the Laravel by the following command.

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

That command will install Laravel project, and next would be to edit the .env file to update your database credentials. Now go to terminal and type 

php artisan migrate

It will create two tables for us in the database.

Step 2: Make model Item.php of our project Laravel Validation

We need to validate our items table in our database, so we need to create one model and one migration for that. So, go to the terminal and type following command.

php artisan make:model Item -m

It will create both Item model as well as create_items_table.

Now, create a controller for Items table

php artisan make:controller ItemController --resource

It will create one controller file with the boilerplate in it.

Step 3: Generate database migrations for items table.

Now, we need to define the database fields in migration. So go to the database >> migrations >> create_migration_table and put the following code in it.

<?php

// create_items_table

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

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

Go to the terminal and type

php artisan migrate

Step 4: Make view file for Laravel Form Validation.

We need to create one view for forms, and then we need to submit that form to our server and check against our validation rules. If any of the rules does not fulfill our requirement, then we need to display an error.

Go to the routes file routes >> web.php and add the following code in it.

// web.php

Route::get('items/add', 'ItemController@create');
Route::post('items/add', 'ItemController@store');

Go to the ItemController file and add the following code in create function.

// ItemController.php

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

Step 5: Made view on Laravel 5.4 Form Validation

I have created one view file inside resources >> views >> itemForm.blade.php

<!-- itemForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <form method="post" action="{{url('items/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>

Step 6: Mass Assignment Exception

The following error will be thrown if you are saving your data in the array format directly.

Possible Errors

Mass assignment exception in Laravel

Possible Solutions

Go to your database table related model and put the following code in it. In my case,  it is an Item.php

// Item.php

protected $fillable = ['name', 'price'];

This will resolve  Mass assignment exception

If you do not define the table name in Model, then Laravel will assume that you have created table “items” because my model name is Item.php. So Laravel always gives table name plural and model name singular. Perfect naming convention in Object Orientated Relational Mapping.

Step 7: Make validation rule in ItemController.php file. 

Now we are going to define very simple validation rule against our form fields. So go to the ItemController.php file and put the following code in store function.  It will automatically redirect to form page if any of the rules gets failed.

// ItemController.php

public function store(Request $request)
{
        $this->validate($request, [
        'name' => 'required|max:10',
        'price' => 'required',
        ]);

        Item::create([
          'name' => $request->get('name'),
          'price'=> $request->get('price')
        ]);

        return back()->with('success', 'You have just created one item');
}

Controller class of Laravel is by default provides us validate method, which takes two arguments.

  1. $request
  2. Our validation rules array

If any of the rules are failed, then It will store an array of the errors and puts into flash session. So in form page, we can get that errors object by calling $errors->all()

So we need to display error in itemForm.blade.php

<!-- itemForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <br />
      @if ($errors->any())
          <div class="alert alert-danger">
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div>
        @endif

        @if (\Session::get('success'))
            <div class="alert alert-success">
                <p>{{ \Session::get('success') }}</p>
            </div>
        @endif      

      <form method="post" action="{{url('items/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>

Now go to the form page by typing URL: http://localhost:8000/items/add 

Do not fill any data and submit the form. You will get some errors like this.

Laravel 5.4 validation example from scratch

This is flash session so after refreshing the page; validation errors are gone. If everything is correct, then you can see the form page that Item is created.

Step 8: Form Request Validation In Laravel 5.4

For more complex validation scenarios, you may wish to create a “form request.” Form requests are custom request classes that contain validation logic. Create a form request class, use the make:request Artisan CLI command:

php artisan make:request FormRequest

Now, we will use the second example, where we do not use validate() function provided by laravel in the controller, we just pass this FormRequest class as a Dependency Injection.

First, we make another controller called FormController

php artisan make:controller FormController --resource

We need to create two more routes for out application.

// web.php

Route::get('formitem/add', 'FormController@create');
Route::post('formitem/add', 'FormController@store');

Now, we need to create one another view called RequestForm.blade.php

<!-- RequestForm.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Item Validation Form</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
  </head>
  <body>
    <div class="container">
      <br />
      @if ($errors->any())
          <div class="alert alert-danger">
              <ul>
                  @foreach ($errors->all() as $error)
                      <li>{{ $error }}</li>
                  @endforeach
              </ul>
          </div>
        @endif
        @if (\Session::get('success'))
            <div class="alert alert-success">
                <p>{{ \Session::get('success') }}</p>
            </div>
          @endif
      <form method="post" action="{{url('formitem/add')}}">
        {{csrf_field()}}
        <div class="form-group">
          <label for="itemName">Item Name:</label>
          <input type="text" class="form-control" id="itemName" name="name">
        </div>
        <div class="form-group">
          <label for="price">Price:</label>
          <input type="text" class="form-control" id="price" name="price">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
      </form>
    </div>
  </body>
</html>

Code the FormController function to return a RequestForm view.

// FormController.php

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

Now, we just need to pass FormRequest as a dependency to the store function of the FormController class.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;
use App\Requests\FormRequest;

class FormController 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('RequestForm');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(FormRequest $request)
    {
        Item::create([
          'name' => $request->get('name'),
          'price'=> $request->get('price')
        ]);
        return back()->with('success', 'You have just created one item');
    }

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

Now, only remaining the thing is that to code the FormRequest file, which is in the app >> Http >> Requests >> FormRequest.php Fill the array of rules function with the validation field.

<?php

// FormRequest.php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'price' => 'required'
        ];
    }
}

Now, go to the following URL: http://localhost:8000/formitem/add

Submit the data without fill the form, and you will get the errors and form will not submit.

For more Validation rules, you can find on official Laravel website.

I have put Laravel 5 validation example from scratch code on GitHub

Github Link: https://github.com/KrunalLathiya/Laravel54Validation

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to the root of the project and run command “composer update
  3. Edit .env file and use your MySQL database credentials.
  4. Run the command “php artisan migrate
  5. Now, we need to bootstrap Laravel server so run “php artisan serve
  6. If now go to this URL: http://localhost:8000/items/add

If you still have doubt in this tutorial, then ask in the comment below, I am happy to help you out.

The post Laravel 5 Validation Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/07/11/laravel-5-4-validation-example-from-scratch/feed/ 4
How to Import and Export Data in CSV in Laravel 5 https://appdividend.com/2017/06/12/import-export-data-csv-excel-laravel-5-4/ https://appdividend.com/2017/06/12/import-export-data-csv-excel-laravel-5-4/#comments Mon, 12 Jun 2017 23:36:36 +0000 http://localhost/wordpress/?p=461 export data in csv in Laravel 5.4

Hii, Web Artists,  In today’s AppDividend Tutorial, I have shown the code of How to import and export data in CSV in Laravel 5. This example is simple laravel excel tutorial. If you want to up and running with basic laravel functionality, then go to my other article on this web blog called Laravel 5.4 Crud Example From Scratch. Import & export […]

The post How to Import and Export Data in CSV in Laravel 5 appeared first on AppDividend.

]]>
export data in csv in Laravel 5.4

Hii, Web Artists,  In today’s AppDividend Tutorial, I have shown the code of How to import and export data in CSV in Laravel 5This example is simple laravel excel tutorial.

If you want to up and running with basic laravel functionality, then go to my other article on this web blog called Laravel 5.4 Crud Example From Scratch.

Import & export data in CSV in Laravel 5.4

We will start this tutorial by installing the maatwebsite/excel package.

Step: 1 Download the maatwebsite/excel package through composer.

composer require maatwebsite/excel

maatwebsite/excel is a Laravel specific package, which provides us some methods to import and export our data from our database.

Step: 2 Add the service provider to the provider’s array in config/app.php file.

Maatwebsite\Excel\ExcelServiceProvider::class,

Step: 3 You can use the facade so, add this to your aliases in config/app.php file.

'Excel' => Maatwebsite\Excel\Facades\Excel::class,

Step: 4 To publish the config settings in Laravel 5.4 use.

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

Step: 5 Create an items table via migration command.

 php artisan make:migration create_items_table

Step: 6 Define columns in our items table.

Go to project folder >> database >> migrations >> items migration file and edit the file.

// 2017_06_13_000837_create_items_table.php

<?php

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
      Schema::create('items', function (Blueprint $table) {
          $table->increments('id');
          $table->string('item_name');
          $table->string('item_code');
          $table->string('item_price');
          $table->integer('item_qty');
          $table->integer('item_tax');
          $table->boolean('item_status');
          $table->timestamp('created_at');
      });
    }

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

Step: 7 Run the migration.

php artisan migrate

Now the table is created in the database. Next step is to build a view for the table to import the file.

Step: 8 Create the items.blade.php file.

// items.blade.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Import-Export Data</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"
  </head>
  <body>
    <div class="container">
      <br />
      <div class="row">
        <div class="col-md-8"></div>
        <div class="col-md-2">
          <button class="btn btn-primary">Import</button>
        </div>
        <div class="col-md-2">
          <button class="btn btn-success">Export</button>
        </div>
      </div>
    </div>
  </body>
</html>

Step: 9 Create an ItemController file.

php artisan make:controller ItemController --resource

Step: 10 Register the route for that item view.

// web.php

Route::get('items', 'ItemController@index');

Step: 11 Write index function in ItemController file.

// ItemController.php

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('items');
    }

Step: 12 Create import form in the view file.

<!--items.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Import-Export Data</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"
  </head>
  <body>
    <div class="container">
      <br />
      <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-6">
          <div class="row">
            <form action="" method="post" enctype="multipart/form-data">
              <div class="col-md-6">
                  <input type="file" name="imported-file"/>
              </div>
              <div class="col-md-6">
                  <button class="btn btn-primary" type="submit">Import</button>
              </div>
            </form>
          </div>
        </div>
        <div class="col-md-2">
          <button class="btn btn-success">Export</button>
        </div>
      </div>
    </div>
  </body>
</html>

Step: 13 Create a model for items table

php artisan make:model Item

so your model will look like this.

// Item.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    protected $fillable = [
      'item_name',
      'item_code',
      'item_price',
      'item_qty',
      'item_tax',
      'item_status',
      'created_at'
    ];
}

Here I have added protected $fillable field to prevent mass assignment exception.

Step: 14 Update the routes and also update actions according to routes.

// web.php

<?php

Route::get('/', function () {
    return view('welcome');
});
Route::get('users', 'UserController@index');

Route::get('items', 'ItemController@index');
Route::post('items/import', 'ItemController@import');

Step: 15 Update items.blade.php according to action provided by routes file web.php

<!-- items.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Import-Export Data</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"
  </head>
  <body>
    <div class="container">
      <br />
      <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-6">
          <div class="row">
            <form action="{{url('items/import')}}" method="post" enctype="multipart/form-data">
              <div class="col-md-6">
                {{csrf_field()}}
                <input type="file" name="imported-file"/>
              </div>
              <div class="col-md-6">
                  <button class="btn btn-primary" type="submit">Import</button>
              </div>
            </form>
          </div>
        </div>
        <div class="col-md-2">
          <button class="btn btn-success">Export</button>
        </div>
      </div>
    </div>
  </body>
</html>

I have also added {{csrf_field()}} to prevent token mismatch exception because this form uses POST request. For more details, please visit https://laravel.com/docs/5.4/csrf

Step: 16 Write import function in ItemController.

// ItemController.php

  /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
      if($request->file('imported-file'))
      {
			    $path = $request->file('imported-file')->getRealPath();
			    $data = Excel::load($path, function($reader) {
			})->get();

			if(!empty($data) && $data->count())
      {
        $data = $data->toArray();
        for($i=0;$i<count($data);$i++)
        {
          $dataImported[] = $data[$i];
        }
			}
      Item::insert($dataImported);
		}
		return back();
  }

I am uploading that excel file in here.  Items Excel File

Now you can upload any excel file and import it, and it can easily be imported into your database.

The new table with inserted values will look like this.

How to import and export data into csv and excel in Laravel 5.4

Now, if the database column names and excel sheet headers are different then we can use following code.

<!-- ItemController.php -->

/**
     * import a file in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function import(Request $request)
    {
      if($request->file('imported-file'))
      {
			    $path = $request->file('imported-file')->getRealPath();
			    $data = Excel::load($path, function($reader)
          {
			    })->get();

          if(!empty($data) && $data->count())
          {
            foreach ($data->toArray() as $row)
            {
              if(!empty($row))
              {
                $dataArray[] =
                [
                  'item_name' => $row['name'],
                  'item_code' => $row['code'],
                  'item_price' => $row['price'],
                  'item_qty' => $row['quantity'],
                  'item_tax' => $row['tax'],
                  'item_status' => $row['status'],
                  'created_at' => $row['created_at']
                ];
              }
          }
          if(!empty($dataArray))
          {
             Item::insert($dataArray);
             return back();
           }
         }
       }
    }

Here is the excel file which has header name and database column name different. Different Header file name

For CSV it works the same so, you can use this code for CSV implementation.

Next step is to Export the files in Excel or CSV format. So first step is to view that table into the items.blade.php

Step: 17 Create table in the items.blade.php file.

<!-- items.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Import-Export Data</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"
  </head>
  <body>
    <div class="container">
      <br />
      <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-6">
          <div class="row">
            <form action="{{url('items/import')}}" method="post" enctype="multipart/form-data">
              <div class="col-md-6">
                {{csrf_field()}}
                <input type="file" name="imported-file"/>
              </div>
              <div class="col-md-6">
                  <button class="btn btn-primary" type="submit">Import</button>
              </div>
            </form>
          </div>
        </div>
        <div class="col-md-2">
          <form action="{{url('items/export')}}" enctype="multipart/form-data">
            <button class="btn btn-success" type="submit">Export</button>
          </form>
        </div>
      </div>
      <div class="row">
        @if(count($items))
        <table class="table table-striped">
          <thead>
            <tr>
              <td>item_name</td>
              <td>item_code</td>
              <td>item_price</td>
              <td>item_qty</td>
              <td>item_tax</td>
              <td>item_status</td>
            </tr>
          </thead>
          @foreach($items as $item)
            <tr>
              <td>{{$item->item_name}}</td>
              <td>{{$item->item_code}}</td>
              <td>{{$item->item_price}}</td>
              <td>{{$item->item_qty}}</td>
              <td>{{$item->item_tax}}</td>
              <td>{{$item->item_status}}</td>
            </tr>
          @endforeach
        </table>
        @endif
      </div>
    </div>
  </body>
</html>

Also, I have defined the action in the export button.

Now create an action in the web.php file.

// web.php

<?php

Route::get('/', function () {
    return view('welcome');
});
Route::get('users', 'UserController@index');

Route::get('items', 'ItemController@index');
Route::post('items/import', 'ItemController@import');
Route::get('items/export', 'ItemController@export');

Step: 18 Create an export function in ItemControlller.php file.

// ItemController.php

/**
     * export a file in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function export(){
      $items = Item::all();
      Excel::create('items', function($excel) use($items) {
          $excel->sheet('ExportFile', function($sheet) use($items) {
              $sheet->fromArray($items);
          });
      })->export('xls');

    }

Now when you press the export button, one .xls file will be downloaded in your browser.

How to import and export data into csv and excel in Laravel 5.4

 This example demonstrates Laravel import CSV or excel to the database.

If you have any doubt in this How to Import and Export Data Laravel 5 tutorial then ask in a comment below, I am happy to help you out.

The post How to Import and Export Data in CSV in Laravel 5 appeared first on AppDividend.

]]>
https://appdividend.com/2017/06/12/import-export-data-csv-excel-laravel-5-4/feed/ 20
How to Generate PDF in Laravel 5 https://appdividend.com/2017/05/08/generate-pdf-blade-laravel-5-4/ https://appdividend.com/2017/05/08/generate-pdf-blade-laravel-5-4/#comments Mon, 08 May 2017 16:05:41 +0000 http://localhost/wordpress/?p=445 generate pdf in laravel 5.4

Greetings, Web Developers,  In today’s AppDividend Tutorial, I have shown the code of How to generate pdf in laravel 5 If you want to know the basic laravel functionality then check out my other article Laravel 5.4 Crud Example From Scratch Generate pdf in laravel 5 First, we will install the laravel-dompdf and then we will start our example. Step: […]

The post How to Generate PDF in Laravel 5 appeared first on AppDividend.

]]>
generate pdf in laravel 5.4

Greetings, Web Developers,  In today’s AppDividend Tutorial, I have shown the code of How to generate pdf in laravel 5

If you want to know the basic laravel functionality then check out my other article Laravel 5.4 Crud Example From Scratch

Generate pdf in laravel 5

First, we will install the laravel-dompdf and then we will start our example.

Step: 1 Download the laravel-dompdf package through composer.

composer require barryvdh/laravel-dompdf

Step: 2 We need to configure this package in our laravel application.

So go to the config >> app.php and add the following configuration.

'providers' => [
	....
	Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
	....
	'PDF' => Barryvdh\DomPDF\Facade::class,
],

Here we are registering the PDF register provider for our application and also set an alias for it. So when we need to generate PDF, we just need to include it in our namespace like,

use PDF;

Then, we instantiate the PDF class and use its API for further enhancing the generated PDF file.

Step: 3 Create a master blade file.

<!-- master.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
      <div class="container">
          @yield('content')
      </div>
  </body>
</html>

Step: 4 Create a form blade file for input the data.

<!-- form.blade.php -->

@extends('master')
@section('content')
<form method="post" action="{{url('submitForm')}}">
    {{csrf_field()}}
    <div class="form-group"> <!-- Full Name -->
      <label for="full_name_id" class="control-label">Full Name</label>
      <input type="text" class="form-control" id="full_name_id" name="full_name" placeholder="John Deer">
    </div>

    <div class="form-group"> <!-- Street 1 -->
      <label for="street1_id" class="control-label">Street Address 1</label>
      <input type="text" class="form-control" id="street1_id" name="street_address" placeholder="Street address, P.O. box, company name, c/o">
    </div>

    <div class="form-group"> <!-- City-->
      <label for="city_id" class="control-label">City</label>
      <input type="text" class="form-control" id="city_id" name="city" placeholder="Smallville">
    </div>

    <div class="form-group"> <!-- Zip Code-->
      <label for="zip_id" class="control-label">Zip Code</label>
      <input type="text" class="form-control" id="zip_id" name="zip_code" placeholder="#####">
    </div>

    <div class="form-group"> <!-- Submit Button -->
      <button type="submit" class="btn btn-primary">Buy!</button>
    </div>

    </form>
@endsection

Step: 5 Add the routes for our application.

// web.php

<?php

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

Route::post('submitForm','UserDetailController@store');

Step: 6 Create the model file for form data.

// UserDetail.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetail extends Model
{
    protected $fillable = ['full_name','street_address','zip_code','city'];
}

Step: 7 Create controller file for form data.

// UserDetailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserDetail;

class UserDetailController extends Controller
{

    public function store(Request $request){

      $user = new UserDetail([
        'full_name' => $request->get('full_name'),
        'street_address' => $request->get('street_address'),
        'city' => $request->get('city'),
        'zip_code' => $request->get('zip_code')
      ]);

      $user->save();
      return redirect('/index');
    }
    public function index(){

      $users = UserDetail::all();

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

Step: 8 Update web.php file for display the listing page.

// web.php

Route::get('/index','UserDetailController@index');

Step: 9 Create a view file for display the data.

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

@extends('master')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Full Name</th>
    <th>Address</th>
    <th>City</th>
    <th>Zip Code</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($users as $user)
    <tr>
      <td>{{$user->id}}</td>
      <td>{{$user->full_name}}</td>
      <td>{{$user->street_address}}</td>
      <td>{{$user->city}}</td>
      <td>{{$user->zip_code}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Step: 10 Create a route for download the pdf file.

/ /web.php

Route::get('/downloadPDF/{id}','UserDetailController@downloadPDF');

Step: 11 Update index.blade.php file.

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

@extends('master')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Full Name</th>
    <th>Address</th>
    <th>City</th>
    <th>Zip Code</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($users as $user)
    <tr>
      <td>{{$user->id}}</td>
      <td>{{$user->full_name}}</td>
      <td>{{$user->street_address}}</td>
      <td>{{$user->city}}</td>
      <td>{{$user->zip_code}}</td>
      <td><a href="{{action('UserDetailController@downloadPDF', $user->id)}}">PDF</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Step: 12 Create pdf.blade.php file to design our pdf blade.

<!-- pdf.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <table class="table table-bordered">
      <tr>
        <td>
          {{$user->full_name}}
        </td>
        <td>
          {{$user->street_address}}
        </td>
      </tr>
      <tr>
        <td>
          {{$user->city}}
        </td>
        <td>
          {{$user->zip_code}}
        </td>
      </tr>
    </table>
  </body>
</html>

Step: 13 Write a controller function to download the PDF.

// UserDetailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;
use App\UserDetail;

class UserDetailController extends Controller
{

    public function store(Request $request){

      $user = new UserDetail([
        'full_name' => $request->get('full_name'),
        'street_address' => $request->get('street_address'),
        'city' => $request->get('city'),
        'zip_code' => $request->get('zip_code')
      ]);

      $user->save();
      return redirect('/index');
    }
    public function index(){

      $users = UserDetail::all();

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

    public function downloadPDF($id){
      $user = UserDetail::find($id);

      $pdf = PDF::loadView('pdf', compact('user'));
      return $pdf->download('invoice.pdf');

    }
}

This was the simple example of laravel pdf generation. Finally, our tutorial on How to Generate PDF in Laravel 5 is over.

The post How to Generate PDF in Laravel 5 appeared first on AppDividend.

]]>
https://appdividend.com/2017/05/08/generate-pdf-blade-laravel-5-4/feed/ 21
Laravel 5.4 Crud Example From Scratch https://appdividend.com/2017/05/02/laravel-5-4-crud-example-scratch/ https://appdividend.com/2017/05/02/laravel-5-4-crud-example-scratch/#comments Tue, 02 May 2017 01:57:56 +0000 http://localhost/final/?p=440 Laravel 5.4 Crud Example From Scratch

Welcome, Web Artisans,  In today’s AppDividend Tutorial, I have shown the code of Laravel 5.4 Crud Example From Scratch. It is simple Laravel 5.4 tutorial for beginners. Laravel For creating Laravel Project, you need to have following things. PHP >= 5.6.4 OpenSSL PHP Extension PDO PHP Extension Mbstring PHP Extension Tokenizer PHP Extension XML PHP Extension Composer Step 1: Create a […]

The post Laravel 5.4 Crud Example From Scratch appeared first on AppDividend.

]]>
Laravel 5.4 Crud Example From Scratch

Welcome, Web Artisans,  In today’s AppDividend Tutorial, I have shown the code of Laravel 5.4 Crud Example From Scratch. It is simple Laravel 5.4 tutorial for beginners.

Laravel

For creating Laravel Project, you need to have following things.

  1. PHP >= 5.6.4
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension
  5. Tokenizer PHP Extension
  6. XML PHP Extension
  7. Composer

Step 1: Create a Laravel project

Type following command in your terminal to create a project.

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

It will take 2 minutes to install a brand new Laravel Framework

After installing, go to your project root folder and type php artisan serve in terminal, your project URL might look like this

http://localhost:8000

Now open that laravel project folder in your favorite editor.

Step 2: Edit .env file for database configuration

In your project root folder, there is a file called .env, which we need to edit to set up a database configuration. I am using MySQL database.

// .env

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

Step 3: Use migrations provided by laravel to create users and password_resets table

Now go to terminal, and run following command

php artisan migrate

If you have created the database in MySQL and you have provided correct credentials to the .env file, then you will see there are three tables generated in MySQL database.

Step 4: Create a controller file for our CRUD operations.

Go to terminal, type the following command in your root project.

php artisan make:controller CRUDController --resource

Now go to laravel54 > app > Http > Controllers, you will see CRUDController file in that folder.

This file has all the boilerplate needed for our Crud operations.

Step 5: Create a model file for CRUD operations.

In the terminal, type the following command in your root project.

php artisan make:model Crud -m

This command will also create a migration file for our CRUD operations.

Step 6: Edit crud migration file and create the required fields for the database.

Migration file is located in laravel54 > database > migrations folder.

<?php
// create_cruds_table

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

class CreateCrudsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cruds', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('post');
            $table->timestamps();
        });
    }

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

Run the following command in your terminal.

php artisan migrate

Step 7: Create views for set up a form

Go to laravel54 > resources > views . Locate into that folder and then create a master view called master.blade.php. A blade is templating engine used by laravel.

<!-- master.blade.php -->

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>CRUD Operations</title>

        <!-- Fonts -->
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <br><br>
        @yield('content')
    </body>
</html>

Now create a new folder inside views directory called crud. Go inside that folder and create following files

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

Step 8: Create a form in create.blade.php

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

@extends('master')
@section('content')
<div class="container">
  <form>
    <div class="form-group row">
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80"></textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <input type="submit" class="btn btn-primary">
    </div>
  </form>
</div>
@endsection

Step 9: Setup a route for the request handling.

Go to the routes > web.php

<?php

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

Here we have added resource route, and all the functions reside in app > Http > controllers > CRUDController

Step 10: Edit CRUDController File

// CRUDController.php

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

Here we have to return the view when the request hits the route; it will be redirected to this controller’s create method. Our view should be accessible via following URL the form.

http://localhost:8000/crud/create

We are now able to see the form with the two fields.

Step 11: Add CSRF token and set the post route of the form.

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

@extends('master')
@section('content')
<div class="container">
  <form method="post" action="{{url('crud')}}">
    <div class="form-group row">
      {{csrf_field()}}
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80"></textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <input type="submit" class="btn btn-primary">
    </div>
  </form>
</div>
@endsection

We have put the {{csrf_field()}} in the form so that malicious attack can not harm our web application.

Step 12: Code the store function and use Crud model to insert the data

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Crud;

class CRUDController 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('crud.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $crud = new Crud([
          'title' => $request->get('title'),
          'post' => $request->get('post')
        ]);

        $crud->save();
        return redirect('/crud');
    }

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

Here we need to create a protected field called $fillable in the Crud model. Otherwise, it will throw a mass assignment exception.

// Crud.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Crud extends Model
{
    protected $fillable = ['title','post'];
}

Now, when you fill the title and post field in our form and submit the form, the new entry will be added to the database. We can confirm it by following steps.

Step 13: Code index() function in the CRUDController File.

//CrudController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Crud;

class CRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cruds = Crud::all()->toArray();
        
        return view('crud.index', compact('cruds'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $crud = new Crud([
          'title' => $request->get('title'),
          'post' => $request->get('post')
        ]);

        $crud->save();
        return redirect('/crud');
    }

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

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

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

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

Step 14: Need to update index.blade.php

<!-- index.blade.php -->
@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Next, shoot the following URL.

http://localhost:8000/crud

You will see a table which has the id, title and post column with their respective data.

Step 15: Add Edit and Delete Button in the index.blade.php

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

@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
        <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td>
        <td><a href="{{action('CRUDController@destroy', $post['id'])}}" class="btn btn-danger">Delete</a></td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Step 16: Create an edit function to pass the data to the edit view.

<?php

// CRUDController.php  
/**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $crud = Crud::find($id);
        
        return view('crud.edit', compact('crud','id'));

    }

Step 17: Create an edit view.

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

@extends('master')
@section('content')
<div class="container">
  <form method="post" action="{{action('CRUDController@update', $id)}}">
    <div class="form-group row">
      {{csrf_field()}}
       <input name="_method" type="hidden" value="PATCH">
      <label for="lgFormGroupInput" class="col-sm-2 col-form-label col-form-label-lg">Title</label>
      <div class="col-sm-10">
        <input type="text" class="form-control form-control-lg" id="lgFormGroupInput" placeholder="title" name="title" value="{{$crud->title}}">
      </div>
    </div>
    <div class="form-group row">
      <label for="smFormGroupInput" class="col-sm-2 col-form-label col-form-label-sm">Post</label>
      <div class="col-sm-10">
        <textarea name="post" rows="8" cols="80">{{$crud->post}}</textarea>
      </div>
    </div>
    <div class="form-group row">
      <div class="col-md-2"></div>
      <button type="submit" class="btn btn-primary">Update</button>
    </div>
  </form>
</div>
@endsection

Here we have used one more hidden field called _method, which will be a PATCH request to the server so that we can update the data very quickly.

Step 18: Code update() in the CRUDController.

<?php
// CRUDController.php

 /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $crud = Crud::find($id);
        $crud->title = $request->get('title');
        $crud->post = $request->get('post');
        $crud->save();
        return redirect('/crud');
    }

After filling the update form, we can see the index page that our data is updated. So now only Delete functionality is remaining.

Step 19: Create a delete form to delete the data.

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

@extends('master')
@section('content')
  <div class="container">
    <table class="table table-striped">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Post</th>
        <th colspan="2">Action</th>
      </tr>
    </thead>
    <tbody>
      @foreach($cruds as $post)
      <tr>
        <td>{{$post['id']}}</td>
        <td>{{$post['title']}}</td>
        <td>{{$post['post']}}</td>
        <td><a href="{{action('CRUDController@edit', $post['id'])}}" class="btn btn-warning">Edit</a></td>
        <td>
          <form action="{{action('CRUDController@destroy', $post['id'])}}" method="post">
            {{csrf_field()}}
            <input name="_method" type="hidden" value="DELETE">
            <button class="btn btn-danger" type="submit">Delete</button>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  </div>
@endsection

Step 20: Code the destroy() method in the CRUDController.

<?php
// CRUDController.php

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

      return redirect('/crud');
    }

Here in delete functionality, we have not put the any confirm box, but it is okay for the demo. I just want you to take this demo and see how the laravel’ flow is working.

Output

Laravel 5.4 Crud Example From Scratch
Laravel 5.4 Crud Example From Scratch

There is some routes list in resource controller. Type in the terminal: php artisan route:list

$ php artisan route:list
+--------+-----------+------------------+--------------+---------------------------------------------+--------------+
| Domain | Method    | URI              | Name         | Action                                      | Middleware   |
+--------+-----------+------------------+--------------+---------------------------------------------+--------------+
|        | GET|HEAD  | /                |              | Closure                                     | web          |
|        | GET|HEAD  | api/user         |              | Closure                                     | api,auth:api |
|        | GET|HEAD  | crud             | crud.index   | App\Http\Controllers\CRUDController@index   | web          |
|        | POST      | crud             | crud.store   | App\Http\Controllers\CRUDController@store   | web          |
|        | GET|HEAD  | crud/create      | crud.create  | App\Http\Controllers\CRUDController@create  | web          |
|        | GET|HEAD  | crud/{crud}      | crud.show    | App\Http\Controllers\CRUDController@show    | web          |
|        | PUT|PATCH | crud/{crud}      | crud.update  | App\Http\Controllers\CRUDController@update  | web          |
|        | DELETE    | crud/{crud}      | crud.destroy | App\Http\Controllers\CRUDController@destroy | web          |
|        | GET|HEAD  | crud/{crud}/edit | crud.edit    | App\Http\Controllers\CRUDController@edit    | web          |

If you are curious how resource controller works behind the scenes, then this is your answer.

Github: https://github.com/KrunalLathiya/Laravel54

 

Steps to use Github code

  1. Clone the repo in your local.
  2. Go to root of the project and run command “composer update
  3. Edit .env file and use your MySQL database credentials.
  4. Run the command “php artisan migrate
  5. Now, we need to bootstrap Laravel server so run “php artisan serve
  6. If now go to this URL: http://localhost:8000/crud/create


If you still have doubt in this Laravel 5.4 Crud Example From Scratch, then ask in the comment below, I am happy to help you out.

The post Laravel 5.4 Crud Example From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2017/05/02/laravel-5-4-crud-example-scratch/feed/ 82