Laravel – AppDividend https://appdividend.com Latest Code Tutorials Fri, 18 Oct 2019 16:20:06 +0000 en-US hourly 1 https://wordpress.org/?v=5.2.4 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Laravel – AppDividend https://appdividend.com 32 32 Laravel 6 Validation Example | Validation In Laravel Tutorial https://appdividend.com/2019/09/21/laravel-6-validation-example-validation-in-laravel-tutorial/ https://appdividend.com/2019/09/21/laravel-6-validation-example-validation-in-laravel-tutorial/#respond Sat, 21 Sep 2019 10:20:35 +0000 http://localhost/wordpress/?p=11420 Laravel 6 Validation Example | Validation In Laravel Tutorial

Laravel 6 Validation Example | Validation In Laravel Tutorial is today’s topic. Laravel provides us the several different methods to validate our application’s data. Out of the box, Laravel’s base controller class uses the ValidatesRequests trait which provides the convenient method to validate an incoming HTTP request with a variety of robust validation rules. Laravel […]

The post Laravel 6 Validation Example | Validation In Laravel Tutorial appeared first on AppDividend.

]]>
Laravel 6 Validation Example | Validation In Laravel Tutorial

Laravel 6 Validation Example | Validation In Laravel Tutorial is today’s topic. Laravel provides us the several different methods to validate our application’s data. Out of the box, Laravel’s base controller class uses the ValidatesRequests trait which provides the convenient method to validate an incoming HTTP request with a variety of robust validation rules.

Laravel 6 Validation Example

Our first step is to install the Laravel 6.

If you are new to Laravel 6, then check out my Laravel 6 CRUD tutorial on this blog.

Right now, Laravel 6 is the latest version. In the future, you may need to specify the version while installing the Laravel 6.

So, install the Laravel 6 using the following command.

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

// or

laravel new laravel6

Create the FormController.php file.

php artisan make:controller FormController

Add two methods inside the FormController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function create()
    {

    }

    public function store(Request $request)
    {
        
    }
}

Now, write the two routes inside the routes >> web.php file, which handles URI of our application.

// web.php

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

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

php artisan make:model Form -m

Write a following code inside the create_forms_table.php file.

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

Now, create the table using the following command.

php artisan migrate

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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

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

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

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Item
  </div>
  <div class="card-body">
      <form method="post" action="{{ route('form.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Item Name:</label>
              <input type="text" class="form-control" name="item_name"/>
          </div>
          <div class="form-group">
              <label for="price">SKU Number :</label>
              <input type="text" class="form-control" name="sku_no"/>
          </div>
          <div class="form-group">
              <label for="quantity">Item Price :</label>
              <input type="text" class="form-control" name="price"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Item</button>
      </form>
  </div>
</div>
@endsection

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

// FormController.php

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

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

Writing A Validation Logic

Write the validation logic inside the FormController’s store() function.

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

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

Now, go to the form and try to submit the form. It won’t send, but you do not see any errors.

Displaying Validation Errors

Okay, so now, we need to write the following snippet inside the create.blade.php file.

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

If an incoming request parameters do not pass the given validation rules, then as mentioned previously, Laravel will automatically redirect a user back to their previous location.

All the validation errors will automatically be flashed to a session.

One thing to notice here that we did not have to explicitly bind all the error messages to a view in the GET route.

It is because Laravel will check for the errors in the session data, and automatically attach them to a view if they are available.

The $errors variable will be the instance of Illuminate\Support\MessageBag.

So, final create.blade.php file is following.

@extends('layout')

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

The $errors variable is bound to a view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by a web middleware group.

When this middleware is applied, the $errors variable will always be available in the views, allowing us to conveniently assume the $errors variable is always defined and can be safely used inside your HTML code.

The @error Directive

You can also use the @error Blade directive to quick check if the validation error messages exist for a given attribute.

Within the @error directive, you may echo the $message variable to display the error message:

<div class="form-group">
   @csrf
   <label for="name">Item Name:</label>
   <input type="text" class="form-control" name="item_name"/>
    @error('item_name')
          <div class="alert alert-danger">{{ $message }}</div>
    @enderror
</div>

Optional Fields

Out of the box, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your app’s global middleware array.

These middleware are included in the stack by an App\Http\Kernel class.

Because of this middleware, you will often need to mark your “optional” request fields as nullable if you do not want a validator to consider the null values as invalid.

For instance:

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

In this example, we are specifying that a publish_at field may be either null or the valid date representation.

If a nullable modifier is not added to the rule definition, a validator would consider null the invalid date.

AJAX Requests & Validation

In this example, we used the traditional form to send data to an app.

However, many applications use the AJAX requests.

When using the validate() method during the AJAX request, Laravel will not generate the redirect response.

Instead, Laravel generates the JSON response containing all of the validation errors. That JSON response will be sent with a 422 HTTP status code.

Form Request Validation In Laravel 6

For more complex validation cases, you may wish to create the “form request”.

Form requests are a custom request classes that contain all the validation logic.

If we need to create the form request class, use the make: request Artisan CLI command:

php artisan make:request ValidateRequest

The generated class will be placed in an app/Http/Requests directory.

If the directory does not exist, it will be generated when you run the make: request command.

Let’s add the few validation rules to the rules method:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'item_name' => 'required|max:255',
            'sku_no' => 'required|alpha_num',
            'price' => 'required|numeric',
        ];
    }
}

So, how are the validation rules evaluated?

All you need to do is type-hint a request on your controller method.

An incoming form request is validated before the controller method is called, meaning we do not need to clutter the controller with any validation logic.

<?php

namespace App\Http\Controllers;

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

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

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

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

Manually Creating Validators

If we do not want to use the validate() method on the request, you may create the validator object manually using the Validator facade.

The make method on a facade generates the new validator instance.

See the following function inside FormController.php file.

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

        if ($validator->fails()) {
            return redirect('form')
                        ->withErrors($validator)
                        ->withInput();
        }

        \App\Form::create([
            'item_name' => $request->item_name, 
            'sku_no' => $request->sku_no,
            'price' => $request->sku_no
        ]);

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

The first argument passed to a make method is the data under validation.

The second argument is the validation rules that should be applied to the data.

After checking if a request validation failed, you may use the withErrors method to flash the error messages to a session.

When using that method, the $errors variable will automatically be shared with your views after redirection, allowing us to display them back to a user easily.

The withErrors method accepts the validator, the MessageBag, or a PHP array.

Named Error Bags

If you have the multiple forms on the single page, you may wish to name the MessageBag of errors, allowing us to retrieve the error messages for the particular form.

Pass the name as the second argument to withErrors:

return redirect('register')
            ->withErrors($validator, 'login');

You may then access the named MessageBag object from the $errors variable.

{{ $errors->login->first('email') }}

Working With The Error Messages

After calling the errors method on a Validator instance, you will receive the Illuminate\Support\MessageBag instance, which has the variety of convenient methods for working with error messages.

The $errors variable which is automatically made available to all the views is also the instance of the MessageBag class.

Retrieving The First Error Message For The Field

If we want to retrieve the first error message for the given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

Retrieving All Error Messages For A Field

If you need to retrieve the array of all of the messages for the given field, use the get method.

foreach ($errors->get('email') as $message) {
    //
}

If you are validating the array form field, you may retrieve all the messages for each of the array items using the * character.

foreach ($errors->get('attachments.*') as $message) {
    //
}

So, we have lots of options to add validation in the form in Laravel 6.

Finally, Laravel 6 Validation Example | Validation In Laravel Tutorial is over.

Recommended Posts

Export Data In Excel and CSV In Laravel 6

Laravel 6 Generate PDF From View Example

Upgrade Laravel Valet And Update To Laravel 6

The post Laravel 6 Validation Example | Validation In Laravel Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/21/laravel-6-validation-example-validation-in-laravel-tutorial/feed/ 0
How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 https://appdividend.com/2019/09/13/how-to-import-and-export-data-in-csv-excel-in-laravel-6/ https://appdividend.com/2019/09/13/how-to-import-and-export-data-in-csv-excel-in-laravel-6/#respond Fri, 13 Sep 2019 11:16:10 +0000 http://localhost/wordpress/?p=11185 How To Export Data In Excel and CSV In Laravel 6 | maatwebsite:excel 3.1

In this tutorial, we will see How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1. If you want to up and running with basic laravel functionality, then go to my other article on this web blog called Laravel 6 Crud Example From Scratch. If you want to Generate PDF In Laravel, […]

The post How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 appeared first on AppDividend.

]]>
How To Export Data In Excel and CSV In Laravel 6 | maatwebsite:excel 3.1

In this tutorial, we will see How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1. If you want to up and running with basic laravel functionality, then go to my other article on this web blog called Laravel 6 Crud Example From ScratchIf you want to Generate PDF In Laravel, then check out Laravel 6 Generate PDF From View Example. For this example, we use the package called maatwebsite/excel version 3.1. So, our Laravel 6 and maatwebsite/excel 3.1.

Export Data In Excel and CSV in Laravel 6

When using the package in your application, it’s good to understand how the package functions behind the scenes. Following the behind-the-scenes will make you feel more comfortable and confident using the maximum potential of the tool.

Laravel Excel 3.1

🚀 Laravel Excel is intended at being Laravel-flavoured PhpSpreadsheet: a simple, but an elegant wrapper around PhpSpreadsheet to simplify the exports and imports.

🔥 PhpSpreadsheet is the library written in pure PHP and providing the set of classes that allow us to read from and to write to different type of spreadsheet file formats, like Excel and LibreOffice Calc.

Laravel Excel Features

  1. We can easily export collections to Excel.
  2. We can export queries with automatic chunking for better performance.
  3. We can queue exports for better performance.
  4. We can easily export Blade views to Excel.
  5. We can easily import to collections.
  6. We can read the Excel file in chunks.
  7. We can handle the import inserts in batches.

Requirements

  1. PHP: ^7.0
  2. Laravel: ^5.5
  3. PhpSpreadsheet: ^1.6
  4. PHP extension php_zip enabled
  5. PHP extension php_xml enabled
  6. PHP extension php_gd2 enabled

Step 1: Installation

Require the following package in the composer.json of your Laravel 6 project. The following command will download the package and PhpSpreadsheet.

composer require maatwebsite/excel
➜  laravel6 git:(master) ✗ composer require maatwebsite/excel
Using version ^3.1 for maatwebsite/excel
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Installing markbaker/matrix (1.1.4): Downloading (100%)
  - Installing markbaker/complex (1.4.7): Downloading (100%)
  - Installing phpoffice/phpspreadsheet (1.9.0): Downloading (100%)
  - Installing maatwebsite/excel (3.1.17): Downloading (100%)
phpoffice/phpspreadsheet suggests installing mpdf/mpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing tecnickcom/tcpdf (Option for rendering PDF with PDF Writer)
phpoffice/phpspreadsheet suggests installing jpgraph/jpgraph (Option for rendering charts, or including charts with PDF or HTML Writers)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: maatwebsite/excel
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.
➜  laravel6 git:(master) ✗

Step 2: Configure package

The Maatwebsite\Excel\ExcelServiceProvider is auto-discovered and registered by default.

If you want to register by yourself, then add the ServiceProvider in config/app.php:

'providers' => [
    /*
     * Package Service Providers...
     */
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

Excel facade is auto-discovered.

If you want to add it manually, add a Facade in config/app.php:

'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]

If you want to publish a config, run the vendor publish command:

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
➜  laravel6 git:(master) ✗ php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Copied File [/vendor/maatwebsite/excel/config/excel.php] To [/config/excel.php]
Publishing complete.
➜  laravel6 git:(master) ✗

This will create the new config file named config/excel.php.

Step 3: Create model and migration files

Type the following command.

php artisan make:model Disneyplus -m

Now, go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up()
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

Now, migrate the database using the following command.

php artisan migrate

Step 4: Create a controller and routes

Next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

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

// web.php

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

Now, create two methods inside the DisneyplusController.php file.

<?php

// DisneyplusController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;

class DisneyplusController extends Controller
{
    public function create()
    {

    }

    public function store()
    {
        
    }
}

Step: 5 Create a form blade file for input the data

Now, inside the views folder, create one file called form.blade.php file. Add the following code.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </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('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

 

Step 6: Store data in the database

Now, we will write the two functions inside the DisneyplusController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;

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

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }
}

So, in the above file, first, we have shown the form file, and then inside the store function, we check for validation and then store the data into the database.

Also, add the fillable fields inside the Disneyplus.php model file.
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Disneyplus extends Model
{
    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Now, go to this route: http://laravel6.test/disneyplus or http://localhost:8000/disneyplus

You will see one form. Try to save the data, and if everything in the code is right, then, you will see one entry in the database.

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

Before we create a view file, we need to add one route inside the web.php.

// web.php

Route::get('disneyplus/list', 'DisneyplusController@index')->name('disneyplus.index');

Now, create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Now, add the code inside the index() function of DisneyplusController.php file.

public function index()
{
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
}

Now, go to the http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list

You will see the listing of the shows.

Step 8: Create Exports class

You may do this by using the make:export command.

php artisan make:export DisneyplusExport --model=Disneyplus

The file can be found in app/Exports directory.

The file DisneyplusExport.php is following.

<?php

namespace App\Exports;

use App\Disneyplus;
use Maatwebsite\Excel\Concerns\FromCollection;

class DisneyplusExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return Disneyplus::all();
    }
}

If you prefer to create a export manually, you can build the following in app/Exports.

Step 9: Write the export function

Inside the DisneyplusController.php file, add the following code.

// DisneyplusController.php

use App\Disneyplus;
use App\Exports\DisneyplusExport;
use Maatwebsite\Excel\Facades\Excel;

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
}

So, our final file looks like below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;
use App\Exports\DisneyplusExport;
use Maatwebsite\Excel\Facades\Excel;

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

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }

    public function index()
    {
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
    }

    public function export() 
    {
        return Excel::download(new DisneyplusExport, 'disney.xlsx');
    }
}

Finally, add the route to be able to access the export:

// web.php

Route::get('export', 'DisneyplusController@export');

Also, add the link to the Export inside the list.blade.php file.

@foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{action('DisneyplusController@export')}}">Export</a></td>
    </tr>
@endforeach

Okay, now finally go to the http://laravel6.test/disneyplus/list, and now you can see one link called Export.

Click on the Export link, and you will see the disney.xlsx file inside your Download folder.

Exporting collections in CSV in Laravel 6

By default, the export format is determined by the extension of the file.

public function export() 
{
        return Excel::download(new DisneyplusExport, 'disney.csv');
}

It will download the CSV file.

If you want to configure the export format explicitly, you can pass it through as 2nd parameter.

You can find more details about export in different formats on this link.

Finally, How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 is over.

The post How To Export Data In Excel and CSV In Laravel 6 | maatwebsite/excel 3.1 appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/13/how-to-import-and-export-data-in-csv-excel-in-laravel-6/feed/ 0
Laravel 6 Generate PDF From View Example Tutorial From Scratch https://appdividend.com/2019/09/13/laravel-6-generate-pdf-from-view-example-tutorial-from-scratch/ https://appdividend.com/2019/09/13/laravel-6-generate-pdf-from-view-example-tutorial-from-scratch/#comments Fri, 13 Sep 2019 08:40:46 +0000 http://localhost/wordpress/?p=11174 Laravel 6 Generate PDF From View Example Tutorial From Scratch

Laravel 6 Generate PDF From View Example Tutorial From Scratch is today’s topic. If you want to know a basic laravel functionality, then check out my article Laravel 6 Crud Example From Scratch. For this example, we use the Dompdf library. Dompdf is an HTML to PDF converter The dompdf is (mostly) the CSS 2.1 compliant HTML layout and […]

The post Laravel 6 Generate PDF From View Example Tutorial From Scratch appeared first on AppDividend.

]]>
Laravel 6 Generate PDF From View Example Tutorial From Scratch

Laravel 6 Generate PDF From View Example Tutorial From Scratch is today’s topic. If you want to know a basic laravel functionality, then check out my article Laravel 6 Crud Example From ScratchFor this example, we use the Dompdf library. Dompdf is an HTML to PDF converter The dompdf is (mostly) the CSS 2.1 compliant HTML layout and rendering engine written in PHP language.

It is the style-driven renderer: it will download and read an external stylesheets, inline style tags, and all the style attributes of individual HTML elements. It also supports most presentational HTML attributes.

Laravel 6 Generate PDF From View

If you are using an older version of Laravel, then check out this How To Generate PDF In Laravel 5 tutorial.

Step: 1 Download the laravel-dompdf package

Type the following command to install the laravel-dompdf package.

composer require barryvdh/laravel-dompdf
➜  laravel6 git:(master) composer require barryvdh/laravel-dompdf
Using version ^0.8.5 for barryvdh/laravel-dompdf
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 5 installs, 0 updates, 0 removals
  - Installing sabberworm/php-css-parser (8.3.0): Downloading (100%)
  - Installing phenx/php-svg-lib (v0.3.3): Downloading (100%)
  - Installing phenx/php-font-lib (0.5.1): Downloading (100%)
  - Installing dompdf/dompdf (v0.8.3): Downloading (100%)
  - Installing barryvdh/laravel-dompdf (v0.8.5): Downloading (100%)
dompdf/dompdf suggests installing ext-imagick (Improves image processing performance)
dompdf/dompdf suggests installing ext-gmagick (Improves image processing performance)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover --ansi
Discovered Package: barryvdh/laravel-dompdf
Discovered Package: facade/ignition
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: laravel/ui
Discovered Package: nesbot/carbon
Discovered Package: nunomaduro/collision
Package manifest generated successfully.

Step: 2 Configure the package laravel 6 application

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

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

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

use PDF;

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

Step: 3 Create a layout blade file

Inside the resources >> views folder, create a new file called layout.blade.php.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Laravel 6 CRUD Example</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>

Step 4: Create model and migration files

We will create model and migration files using the following command.

php artisan make:model Disneyplus -m

Now, go to the [timestamp].create_disneypluses_table.php file and add the columns.

public function up()
{
        Schema::create('disneypluses', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('series');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

Now, migrate the database using the following command.

php artisan migrate

Step 5: Create a controller and routes

Next step is to create a DisneyplusController.php file.

php artisan make:controller DisneyplusController

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

// web.php

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

Now, create two methods inside the DisneyplusController.php file. 

<?php

namespace App\Http\Controllers;

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

class DisneyplusController extends Controller
{
    public function create()
    {

    }

    public function store()
    {
        
    }
}

Remember to import the PDF module by use PDF; code.

Step: 6 Create a form blade file for input the data

Now, inside the views folder, create one file called form.blade.php file. Add the following code.

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Add Disneyplus Shows
  </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('disneyplus.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Series :</label>
              <input type="text" class="form-control" name="series"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

Step 7: Store data in the database

Now, we will write the two functions inside the DisneyplusController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Disneyplus;

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

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'series' => 'required|max:255',
            'lead_actor' => 'required|max:255',
        ]);
        Disneyplus::create($validatedData);
   
        return redirect('/disneyplus')->with('success', 'Disney Plus Show is successfully saved');
    }
}

So, in the above file, first, we have shown the form file, and then inside the store function, we check for validation and then store the data into the database.

Also, add the fillable fields inside the Disneyplus.php model file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Disneyplus extends Model
{
    protected $fillable = ['show_name', 'series', 'lead_actor'];
}

Now, go to this route: http://laravel6.test/disneyplus or http://localhost:8000/disneyplus

You will see one form. Try to save the data, and if everything in the code is right, then, you will see one entry in the database.

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

Before we create a view file, we need to add one route inside the web.php.

// web.php

Route::get('disneyplus/list', 'DisneyplusController@index')->name('disneyplus.index');

Now, create a view file called list.blade.php file. Add the following code.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

Now, add the code inside the index() function of DisneyplusController.php file.

public function index()
{
        $shows = Disneyplus::all();

        return view('list', compact('shows'));
}

Now, go to the http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list

You will see the listing of the shows.

Step: 9 Create a route to download the pdf file

Add the following code inside the route file.

// web.php

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

Now, update the list.blade.php file and add the Download PDF link.

@extends('layout')
@section('content')
<table class="table table-striped">
  <thead>
    <th>ID</th>
    <th>Show Name</th>
    <th>Series</th>
    <th>Lead Actor</th>
    <th>Action</th>
  </thead>
  <tbody>
    @foreach($shows as $show)
    <tr>
      <td>{{$show->id}}</td>
      <td>{{$show->show_name}}</td>
      <td>{{$show->series}}</td>
      <td>{{$show->lead_actor}}</td>
      <td><a href="{{action('DisneyplusController@downloadPDF', $show->id)}}">Download PDF</a></td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

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

You can create the new DOMPDF instance and load an HTML string, file, or blade view name. You can save it to the file, or stream.

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

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <table class="table table-bordered">
    <thead>
      <tr>
        <td><b>Show Name</b></td>
        <td><b>Series</b></td>
        <td><b>Lead Actor</b></td>     
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>
          {{$show->show_name}}
        </td>
        <td>
          {{$show->series}}
        </td>
        <td>
          {{$show->lead_actor}}
        </td>
      </tr>
      </tbody>
    </table>
  </body>
</html>

We have created a simple table which will be generated inside the PDF.

Step: 11 Write a controller function to download the PDF

Write the following code inside the DisneyplusController.php file.

// DisneyplusController.php

public function downloadPDF($id) {
        $show = Disneyplus::find($id);
        $pdf = PDF::loadView('pdf', compact('show'));
        
        return $pdf->download('disney.pdf');
}

Now, go to the http://laravel6.test/disneyplus/list or http://localhost:8000/disneyplus/list and click on the Download PDF link.

You will see that it downloads the PDF file and open that PDF, you will see the table contains show listings.

Conclusion

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

The post Laravel 6 Generate PDF From View Example Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/13/laravel-6-generate-pdf-from-view-example-tutorial-from-scratch/feed/ 1
Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners https://appdividend.com/2019/09/12/laravel-6-crud-example-laravel-6-tutorial-for-beginners/ https://appdividend.com/2019/09/12/laravel-6-crud-example-laravel-6-tutorial-for-beginners/#comments Thu, 12 Sep 2019 10:41:31 +0000 http://localhost/wordpress/?p=11133 Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners

Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners is today’s topic. We can upgrade your Laravel’s 6 versions by going to this link. Laravel 6 continues the improvements made in Laravel 5.8 by introducing the following features. Semantic versioning Compatibility with Laravel Vapor, Improved authorization responses, Job middleware, Lazy collections, Sub-query improvements, The extraction […]

The post Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners appeared first on AppDividend.

]]>
Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners

Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners is today’s topic. We can upgrade your Laravel’s 6 versions by going to this link. Laravel 6 continues the improvements made in Laravel 5.8 by introducing the following features.

  1. Semantic versioning
  2. Compatibility with Laravel Vapor,
  3. Improved authorization responses,
  4. Job middleware,
  5. Lazy collections,
  6. Sub-query improvements,
  7. The extraction of frontend scaffolding to the laravel/ui Composer package

#Server Requirements For Laravel 6

See the following server requirements to run Laravel 6.

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

#Prerequisites

For this Laravel 6 crud project, I am using the Visual Studio Code as an editor for my project. If you do not know how to set the PHP on VSCode, then we have a perfect tutorial on this blog on how to configure Visual Studio Code For PHP Developers.

Laravel 6 CRUD Tutorial With Example

On this blog, we have already written Laravel 5.6 CRUDLaravel 5.7 CRUD, Laravel 5.8 CRUD.

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

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

Now, go inside the laravel6 folder. You need to install the frontend dependencies using the following command.

npm install

Step 1: Configure the MySQL Database

I have created the MySQL database called laravel6 and now write the MySQL credentials inside a .env file.

Before creating migrations, we need to set up MySQL database, assuming you know how to create the database using PHPMyAdmin.

After creating a database, we will add database credentials in our application. Laravel has the .env environment file which will have all the sensitive data like database details, mail driver details, etc.

Because it’s not recommended to save such information directly inside a code (environment files are not limited to just PHP, they are used in all other frameworks).

Values inside a .env file are loaded inside the files from the config directory. A .env file is located at the root of our laravel project.

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

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

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

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

php artisan migrate

You will see that three tables will create inside the MySQL Databases.

In Laravel 6, you see one more table called create_failed_jobs_table

Laravel 6 CRUD Tutorial With Example

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

Step 2: Create the model and migration files

We have already set up our database, now let’s see at database migrations. Migration is used to save the details about the database table, and it’s the properties, so you don’t have to manually generate all of the tables by going to the database interface or something like phpmyadmin.

We can develop the migrations using artisan with “make: migration” command.

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

php artisan make:model Show -m

In laravel, the name of a model has to be singular, and the name of the migration should be the plural so it can automatically find a table name.

You can find these migration files inside the database/migrations directory.

Laravel comes with three migrations, namely users, failed_jobs, and the password_resets (all migration files are prepended with a timestamp), which are used for authentication.

If you want to create the migration but have a different table name in mind, then you can explicitly define a table name with “ — create” flag.

It will create the Show.php file and [timestamp]create_shows_table.php migration file.

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

When you open a create_books_table.php, you will see two methods, up() and down().

The up() function is used for creating/updating tables, columns, and indexes. The down() function is used for reversing an operation done by up() method.

Inside up() function, We have the Schema: create(‘table_name,’ callback) method which will be used for creating the new table.

Inside a callback, we have $table->bigIncrements(‘id’) which will create the auto_increment integer column with the primary key and argument ‘id’ is the name of a column.

Second is $table->timestamps() which will create the two timestamp columns created_at and updated_at. The created_at will be filled when the row is created and updated_at when the row is updated.

Now, add the following columns.

public function up()
{
        Schema::create('shows', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('show_name');
            $table->string('genre');
            $table->float('imdb_rating');
            $table->string('lead_actor');
            $table->timestamps();
        });
}

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

php artisan migrate

The command will run the migrations and create defined tables. It will execute the up() function.

If you need to reverse the migrations, you can use the migrate: rollback command which will execute the down() function like php artisan migrate:rollback.

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Show extends Model
{
    protected $fillable = ['show_name', 'genre', 'imdb_rating', 'lead_actor'];
}

We can specify all the properties to modify the behavior of the model.

We can write a $table property which is used to determine a name of the table that this model will interact with in the future operations.

By default, It will define a table name as the plural of the model name, e.g., shows table for Show model and users table for User model.

When you don’t need to use timestamps on your table, then you will also have to specify the $timestamps property and set it to false value in your Model because Laravel expects your table to have the created_at and updated_at timestamp columns.

Step 3: Create routes and controller

First, create the ShowController using the following command.

php artisan make:controller ShowController --resource

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

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

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

<?php

// ShowController.php

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

Route::resource('shows', 'ShowController');

We can pass dynamic parameters with {} brackets, and you might have noticed that show, update, and destroy has the same url but different methods, so it’s legit.

Just like — resource flag, laravel has a method called resource() that will generate all the above routes. You can also use that method instead of specifying them individually like above.

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

Laravel 6 Tutorial For Beginners

Step 4: Configure Bootstrap 4

Right now, there are some issues, or somehow I do not see any code inside the public >> css >> app.css file. I have already compiled the CSS and JS file by the npm run dev command, but still, the app.css file is empty.

One possible solution is to copy the code of the previous version’s Laravel’s app.css file and paste it here inside the Laravel 6 folder’s public >> css >> app.css file like the following. I have put the link of the previous css file.

https://raw.githubusercontent.com/KrunalLathiya/Laravel58CRUD/master/public/css/app.css

Now, the second possible solution is this. This new scaffolding is only available in Laravel 6 and not in the earlier versions like Laravel 5.8 or 5.7.

While Laravel 6 does not dictate which JavaScript or CSS pre-processors you use, it does provide the essential starting point using Bootstrap and Vue that will be helpful for many projects.

By default, the Laravel uses the NPM to install both of these frontend packages.

Bootstrap and Vue scaffolding provided by Laravel is located in the laravel/ui Composer package, which you can install using Composer via the following command:

composer require laravel/ui --dev

 

Configure Bootstrap 4

Once the laravel/ui package has been installed, and you may install the frontend scaffolding using the ui Artisan command:

// Generate basic scaffolding...
php artisan ui vue
php artisan ui react

// Generate login / registration scaffolding...
php artisan ui vue --auth
php artisan ui react --auth

Step 5: Create the views

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

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

Inside the views folder, we also need to create the layout file.

So create a file inside the views folder called layout.blade.php. Add the following code inside a 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 6 CRUD Example</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 is our main template file, and all the other view files will extend this layout.blade.php file.

Here, we have already included the Bootstrap 4 by adding the app.css.

Next step would be to code a 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 Shows
  </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('shows.store') }}">
          <div class="form-group">
              @csrf
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name"/>
          </div>
          <div class="form-group">
              <label for="price">Show Genre :</label>
              <input type="text" class="form-control" name="genre"/>
          </div>
          <div class="form-group">
              <label for="price">Show IMDB Rating :</label>
              <input type="text" class="form-control" name="imdb_rating"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor"/>
          </div>
          <button type="submit" class="btn btn-primary">Create Show</button>
      </form>
  </div>
</div>
@endsection

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

// ShowController.php

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

Go to a http://localhost:8000/books/create or http://laravel6.test/shows/create

You will see something like following.

Create the views

Step 6: Add Validation rules and save data

In this step, we will add a Laravel Validation.

Now, the first step inside the ShowController.php is that import the namespace of Show model inside the ShowController.php file.

<?php

// ShowController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Show;

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

public function store(Request $request)
{
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'genre' => 'required|max:255',
            'imdb_rating' => 'required|numeric',
            'lead_actor' => 'required|max:255',
        ]);
        $show = Show::create($validatedData);
   
        return redirect('/books')->with('success', 'Show is successfully saved');
 }

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

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

Store method has $request object as the parameter which will be used to access form data. 

The first thing you want to do is validate a form of data.

We can use a $request->validate() function for validation, which will receive the array of validation rules.

Validation rules is an associative array.

Key will be the field_name and value with being the validation rules. 

The second parameter is the optional array for custom validation messages.

Rules are separated with pipe sign “|.” We are using the most basic validation rules.

First is “required,” which means the field_name should not be empty. (“nullable” rule is vice versa), “string” means it should be the string value, “min” is the limit of minimum characters for a string in an input field and “max” is the maximum characters. “unique:table, column” with see if the same value does not exists in the database (comes handy for storing emails or any other unique data).

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

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

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

Add Validation rules and save data

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

created a new Show

Step 7: Display the data

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

// ShowController.php

public function index()
{
     $shows = Show::all();

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

Okay, now create a file called index.blade.php inside the views folder 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>Show Name</td>
          <td>Show Genre</td>
          <td>Show IMDB Rating</td>
          <td>Lead Actor</td>
          <td colspan="2">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($shows as $show)
        <tr>
            <td>{{$show->id}}</td>
            <td>{{$show->show_name}}</td>
            <td>{{$show->genre}}</td>
            <td>{{number_format($show->imdb_rating,2)}}</td>
            <td>{{$show->lead_actor}}</td>
            <td><a href="{{ route('shows.edit', $show->id)}}" class="btn btn-primary">Edit</a></td>
            <td>
                <form action="{{ route('shows.destroy', $show->id)}}" method="post">
                  @csrf
                  @method('DELETE')
                  <button class="btn btn-danger" type="submit">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

We have used the PHP number_format() function to print the IMDB Rating float value.

Here, we have looped through the show’s array and display the data in the table format.

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

Step 8: Create Edit and Update Operation

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

// ShowController.php

public function edit($id)
{
     $show = Show::findOrFail($id);

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

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

@extends('layout')

@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="card uper">
  <div class="card-header">
    Update Shows
  </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('shows.update', $show->id) }}">
          <div class="form-group">
              @csrf
              @method('PATCH')
              <label for="name">Show Name:</label>
              <input type="text" class="form-control" name="show_name" value="{{ $show->show_name }}"/>
          </div>
          <div class="form-group">
              <label for="price">Show Genre :</label>
              <input type="text" class="form-control" name="genre" value="{{ $show->genre }}"/>
          </div>
          <div class="form-group">
              <label for="price">Show IMDB Rating :</label>
              <input type="text" class="form-control" name="imdb_rating" value="{{ number_format($show->imdb_rating, 2) }}"/>
          </div>
          <div class="form-group">
              <label for="quantity">Show Lead Actor :</label>
              <input type="text" class="form-control" name="lead_actor" value="{{ $show->lead_actor }}"/>
          </div>
          <button type="submit" class="btn btn-primary">Update Show</button>
      </form>
  </div>
</div>
@endsection

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

So, when you hit this URL: http://localhost:8000/shows/1/edit or http://laravel6.test/shows/1/edit, you will see something like the below image.

Create Edit and Update Operation

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

// ShowController.php

public function update(Request $request, $id)
{
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'genre' => 'required|max:255',
            'imdb_rating' => 'required|numeric',
            'lead_actor' => 'required|max:255',
        ]);
        Show::whereId($id)->update($validatedData);

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

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

Step 9: Create Delete Functionality

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

// ShowController.php

public function destroy($id)
{
        $show = Show::findOrFail($id);
        $show->delete();

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

Go to the URL: http://localhost:8000/shows and try to remove the show.

You can see that you have successfully deleted the Show.

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

<?php

// ShowController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Show;

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'show_name' => 'required|max:255',
            'genre' => 'required|max:255',
            'imdb_rating' => 'required|numeric',
            'lead_actor' => 'required|max:255',
        ]);
        $show = Show::create($validatedData);
   
        return redirect('/books')->with('success', 'Show is successfully saved');
    }

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

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

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

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

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

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

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

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

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

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

Github Code

Recommended Posts

How To Export Data In Excel and CSV In Laravel 6

Laravel 6 Generate PDF From View Example

How To Upgrade Laravel Valet And Update To Laravel 6

Laravel Collections Search Method Tutorial

Laravel Collections Filter Method Tutorial

Laravel File Upload Example

Laravel Multiple Files Upload Tutorial Example

Laravel Ajax Validation Tutorial From Scratch

Laravel AJAX Tutorial Example

The post Laravel 6 CRUD Example | Laravel 6 Tutorial For Beginners appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/12/laravel-6-crud-example-laravel-6-tutorial-for-beginners/feed/ 4
How To Upgrade Laravel Valet And Update To Laravel 6 https://appdividend.com/2019/09/04/how-to-upgrade-laravel-valet-and-update-to-laravel-6/ https://appdividend.com/2019/09/04/how-to-upgrade-laravel-valet-and-update-to-laravel-6/#respond Wed, 04 Sep 2019 08:43:28 +0000 http://localhost/wordpress/?p=11025 How To Upgrade Laravel Valet And Update To Laravel 6

In this tutorial, we will see How To Upgrade Laravel Valet And Update To Laravel 6. As a title suggests, we are using Laravel Valet to create a brand new Laravel project. But, when the latest version of Laravel arrives, we need first to upgrade the Laravel Valet then we can create a new version’s […]

The post How To Upgrade Laravel Valet And Update To Laravel 6 appeared first on AppDividend.

]]>
How To Upgrade Laravel Valet And Update To Laravel 6

In this tutorial, we will see How To Upgrade Laravel Valet And Update To Laravel 6. As a title suggests, we are using Laravel Valet to create a brand new Laravel project. But, when the latest version of Laravel arrives, we need first to upgrade the Laravel Valet then we can create a new version’s Laravel project otherwise it will create an old version’s Laravel project.

How To Upgrade Laravel Valet

Okay, so first, you had to have installed Laravel valet in your machine and now go to a terminal and type the following command.

composer global update

So, it will update the Laravel valet and related all the environmental dependency globally.

After upgrading, it is a better habit to run a valet install command so Valet can make the additional upgrades to your configuration files if necessary. See the below command.

valet install

After upgrading, it may be required to re-park or re-link your sites.

I have already sites folder. So, I will navigate to that folder and park my folder using the following command.

valet park

Create Laravel 6 Project

Next, create a new Laravel project in the sites directory by the following command.

laravel new laravel6

It will start crafting a new Laravel application.

 

How To Upgrade Laravel Valet

Now, go inside the folder and check the version of the new Laravel application by the following command.

➜  laravel6 php artisan --version
Laravel Framework 6.0.0
➜  laravel6

In the above output, we have got the Laravel 6, which is the current latest version.

Now, go to a browser and hit the following address to get the Laravel app’s default page.

http://laravel6.test/

Now, we can access the site in your browser at  http://laravel6.test.

The link Command

If we want to use the command, navigate to one of your projects, and run the valet link app-name in your command-line tool. Valet will create the symbolic link in ~/.config/valet/Sites, which points to your current working directory.

After running a link command, you can access your website in your browser at http://app-name.test.

In our case, it is http://laravel6.test/

Finally, How To Upgrade Laravel Valet And Update To Laravel 6 Tutorial is over.

The post How To Upgrade Laravel Valet And Update To Laravel 6 appeared first on AppDividend.

]]>
https://appdividend.com/2019/09/04/how-to-upgrade-laravel-valet-and-update-to-laravel-6/feed/ 0
Laravel Collections Search Method Tutorial With Example https://appdividend.com/2019/04/08/laravel-collections-search-method-tutorial-with-example/ https://appdividend.com/2019/04/08/laravel-collections-search-method-tutorial-with-example/#respond Mon, 08 Apr 2019 17:39:36 +0000 http://localhost/wordpress/?p=5770 Laravel Collections Search Method Tutorial With Example

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

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

]]>
Laravel Collections Search Method Tutorial With Example

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

Laravel Collections Search Method

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

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

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

     return false;
}

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

See the following example.

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

<?php

// web.php

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

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

});

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

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

<?php

// app.php

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

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

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

<?php

// app.php

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

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

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

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

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

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

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

]]>
Laravel Collections Filter Method Example

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

Laravel Collections Filter Method

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

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

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

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

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

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

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

Write the following code inside the web.php file.

<?php

// web.php

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

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

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

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

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

php artisan serve

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

Laravel Collections Filter Method Tutorial With Example

 

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

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

<?php

// web.php

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

    $filtered = $collection->filter();

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

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

Laravel Collections Filter Method

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

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

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

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

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

]]>
How To Create Multilingual Website using Laravel Localization

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

Create Multilingual Website using Laravel Localization

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

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

Step 1: Install Laravel 5.8

Type the following command in your terminal.

laravel new localization

or

composer create-project laravel/laravel localization

 

Laravel Localization

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

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

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

// app.php 

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

    'locale' => 'en',

Here, the locale is set to en.

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

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

<?php

// auth.php

return [

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

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

];

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

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

<?php

// auth.php

return [

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

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

];

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

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

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

Step 2: Creating Translation Files

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

  1. French
  2. Spanish
  3. Japanese

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

 

Website using Laravel Localization

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

For en >> sentence.php file,

<?php

// sentence.php

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

For es >> sentence.php file,

<?php

// sentence.php

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

For fr >> sentence.php file,

<?php

// sentence.php

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

And last, jp >> sentence.php file.

<?php

// sentence.php

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

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

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

Step 3: Setup the view.

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

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

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

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

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

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

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

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

                    </ul>

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

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

@extends('layouts.app')

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

Step 4: Setup route, controller, and middleware

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

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

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

php artisan make:controller HomeController

Write the following code inside that file.

<?php

// HomeController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App;

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

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

Now, create a middleware using the following command.

php artisan make:middleware Localization

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

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

<?php

// Localization.php

namespace App\Http\Middleware;

use Closure;
use App;

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

Step 5: Register the Localization Middleware

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

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

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

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

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

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

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

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

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

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

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

                    </ul>

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

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

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

@extends('layouts.app')

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

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

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

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

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

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

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

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

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

]]>
Laravel 5.8 Seeding

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

Laravel Model Factories Tutorial

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

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

composer require fzaninotto/faker

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

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

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

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

php artisan make:model Internet -m

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

// create_internets_table.php

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

Now, migrate using the following command.

php artisan migrate

Also, create an InternetFactory by using the following command.

php artisan make:factory InternetFactory

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

<?php

// InternetFactory.php

use Faker\Generator as Faker;

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

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

<?php

// InternetFactory.php

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

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

The $faker->safeEmail will create fake safeEmail.

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

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

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

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

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

Laravel Database Seeding

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

php artisan make:seeder InternetsTableSeeder

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

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

Write the following code inside that file.

<?php

// InternetsTableSeeder.php

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

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

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

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

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

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

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

composer dump-autoload

Then type the following command.

php artisan db:seed

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Fake Data

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

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding

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

Testing Model Factories

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

php artisan make:test InternetsTest

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

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

<?php

// InternetsTest.php

namespace Tests\Feature;

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

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

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

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

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

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

See the output below.

 

Testing Model Factories

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

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

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

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

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

]]>
Laravel Eloquent Collection Tutorial Example

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

Laravel Eloquent Collection Tutorial

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

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

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

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

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

php artisan migrate

Seed Database

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

Create a UsersTableSeeder.php file using the following command.

php artisan make:seeder UsersTableSeeder

We will use Model factories to generate fake data.

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

<?php

// UsersTableSeeder.php

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

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

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

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

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

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

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

composer dump-autoload

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

php artisan db:seed

It will generate fake data in the users table.

Laravel Eloquent Collection Tutorial

 

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

Query Data using Laravel Eloquent Collection

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

<?php

// web.php

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

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

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

 

Laravel 5.8 Guide

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

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

Laravel chunk() Collection Method

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

Write the following code inside the web.php file.

<?php

// web.php

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

The output of the above code is following.

 

Laravel chunk() Collection Method

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

Laravel Custom Collections

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

<?php

// User.php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

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

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

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

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

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

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

<?php

// CustomCollection.php

namespace App;

use Illuminate\Support\Collection;

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

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

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

<?php

// web.php

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

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

 

Laravel Custom Collections

Finally, Laravel Eloquent Collection Tutorial With Example is over.

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

]]>
https://appdividend.com/2019/03/10/laravel-eloquent-collection-tutorial-with-example/feed/ 1