Categories
Laravel

CRUD in Laravel 5.8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 5.8. Laravel is one of the fastest growing frameworks for PHP built by Taylor Otwell.

# Laravel 5.8

Laravel 5.8 continues the improvements made in the previous release (version 5.7). ReferΒ release notesΒ to see the changes made in Laravel 5.8.

In this tutorial, You’ll learn the Basic CRUD operation in Laravel. Follow the step by step guide to create the CRUD application.

  1. Install Laravel

First, let install Laravel using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel students
Code language: PHP (php)
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: PHP (php)
  1. Create the migration file.

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

php artisan make:migration create_students_table --create=students
Code language: PHP (php)

The migration will be created under “database/migrations“. Edit the file with the code below to create Students Table.

create_students_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->text('detail'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } }
Code language: Ceylon (ceylon)

Type the following command to run the migration.

php artisan migrate
  1. Create route, controller and model

In this step, Go to ‘routes->web.php’ file, add the following line of code.

//redirect to the students resource controller Route::get('/', function () { return redirect('/students'); }); Route::resource('students','StudentController');
Code language: PHP (php)

Create the Student model using the following command.

php artisan make:model Student
Code language: PHP (php)

The model wil be generated in “app/Student.php” Now, we will write the schema inside Student.php file.

Student.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Student extends Model { protected $fillable = [ 'name', 'detail' ]; }
Code language: PHP (php)

Create the StudentController as resource using the following command.

php artisan make:controller StudentController --resource --model=Student
Code language: PHP (php)

app/Http/Controllers/StudentController.php

<?php namespace App\Http\Controllers; use App\Student; use Illuminate\Http\Request; class StudentController extends Controller { public function index() { $students = Student::latest()->paginate(5); return view('students.index',compact('students'))->with('i', (request()->input('page', 1) - 1) * 5); } public function create() { return view('students.create'); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'detail' => 'required', ]); Student::create($request->all()); return redirect()->route('students.index')->with('success','Student created successfully.'); } public function show(Student $student) { return view('students.show',compact('student')); } public function edit(Student $student) { return view('students.edit',compact('student')); } public function update(Request $request, Student $student) { $request->validate([ 'name' => 'required', 'detail' => 'required', ]); $student->update($request->all()); return redirect()->route('students.index')->with('success','Student updated successfully.'); } public function destroy(Student $student) { $student->delete(); return redirect()->route('students.index')->with('success','Student deleted successfully.'); } }
Code language: PHP (php)
  1. Create the view Files

You need to create a folder Inside resources -> views as students. Inside that folder, create the following five files.

  1. layout.blade.php
  2. index.blade.php
  3. create.blade.php
  4. edit.blade.php
  5. show.blade.php

resources/views/students/layout.blade.php

<!DOCTYPE html> <html> <head> <title>Laravel 6.0,5.8 CRUD Application - bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="card" style="margin-top: 20px;"> <div class="card-body"> @yield('content') </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

resources/views/students/index.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Simple Student Management CRUD Application</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-success " href="{{ route('students.create') }}"> Add Student</a> </div> </div> @if ($message = Session::get('success')) <div class="alert alert-success"> {{ $message }} </div> @endif @if(sizeof($students) > 0) <table class="table table-bordered"> <tr> <th>No</th> <th>Name</th> <th>Details</th> <th width="280px">More</th> </tr> @foreach ($students as $student) <tr> <td>{{ ++$i }}</td> <td>{{ $student->name }}</td> <td>{{ $student->detail }}</td> <td> <form action="{{ route('students.destroy',$student->id) }}" method="POST"> <a class="btn btn-info" href="{{ route('students.show',$student->id) }}">Show</a> <a class="btn btn-primary" href="{{ route('students.edit',$student->id) }}">Edit</a> @csrf @method('DELETE') <button type="submit" class="btn btn-danger">Delete</button> </form> </td> </tr> @endforeach </table> @else <div class="alert alert-alert">Start Adding to the Database.</div> @endif {!! $students->links() !!} @endsection
Code language: HTML, XML (xml)

resources/views/students/create.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Add Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <strong>Oops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('students.store') }}" method="POST"> @csrf <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> <input type="text" name="name" class="form-control" placeholder="Name"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Detail:</strong> <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
Code language: HTML, XML (xml)

resources/views/students/edit.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Edit Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> @if ($errors->any()) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="{{ route('students.update',$student->id) }}" method="POST"> @csrf @method('PUT') <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> <input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Detail:</strong> <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $student->detail }}</textarea> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12 text-center"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> @endsection
Code language: HTML, XML (xml)

resources/views/students/show.blade.php

@extends('students.layout') @section('content') <div class="row"> <div class="col-lg-12"> <h2 class="text-center">Show Student</h2> </div> <div class="col-lg-12 text-center" style="margin-top:10px;margin-bottom: 10px;"> <a class="btn btn-primary" href="{{ route('students.index') }}"> Back</a> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Name:</strong> {{ $student->name }} </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="form-group"> <strong>Details:</strong> {{ $student->detail }} </div> </div> </div> @endsection
Code language: HTML, XML (xml)

Finally, Laravel CRUD Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve
Code language: PHP (php)

Hope this tutorial helps you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Import, Export from Excel to Database in Laravel 5.8, 5.7, 5.6.

This tutorial is created to Import, Export data from an excel sheet to database in Laravel Framework using maatwebsite/excel package. It provides an easy way to import and export using database model. It will work with Laravel 5.8, 5.7, 5.6.

Read Excel files in Laravel
Laravel Import, Export – Excel CSV
  1. Install Laravel

First, let’s install Laravel using the following command (Make sure, You have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel excelApplication
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Install Maatwebsite/excel Package

Install Mattwebsite/excel package via the composer manager, use the terminal to run the command below.

composer require maatwebsite/excel
Code language: JavaScript (javascript)
  1. Specify the configuration

After installing maatwebsite/excel package, Go to config/app.php file and add the service provider and aliase.

config/app.php

'providers' => [ .... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ .... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ],
Code language: PHP (php)

Type the following command to publish the above configuration settings. If you’re prompt with provide tag files, Choose “Provider: Maatwebsite\Excel\ExcelServiceProvider” to publish.

php artisan vendor:publish
Code language: CSS (css)
  1. Create a database model and migration

In this step, we’re going to create a Data model and migration

php artisan make:model Data --migration
Code language: CSS (css)

The migration will be created under “database/migrations”. Edit the file with the code below to create Data Table.

‘date’_create_data_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDataTable extends Migration { public function up() { Schema::create('data', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('data'); } }
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate

Open the generated model in “app/Data.php” Now, Write the schema inside Data.php file.

app/Data.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Data extends Model { protected $fillable = ['title','description']; }
Code language: HTML, XML (xml)
  1. Create DataController

Type the following command at your terminal to create DataController.php file in controllers

php artisan make:controller DataController
Code language: CSS (css)

app/Http/Controllers/DataController.php

<?php namespace App\Http\Controllers; use App\Data; use Excel; use Illuminate\Http\Request; class DataController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { return view('index'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function downloadData($type) { $data = Data::get()->toArray(); return Excel::create('excel_data', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function importData(Request $request) { $request->validate([ 'import_file' => 'required' ]); $path = $request->file('import_file')->getRealPath(); $data = Excel::load($path)->get(); if($data->count()){ foreach ($data as $key => $value) { $arr[] = ['title' => $value->title, 'description' => $value->description]; } if(!empty($arr)){ Data::insert($arr); } } return back()->with('success', 'Insert Record successfully.'); } }
Code language: HTML, XML (xml)

In this step, Go to ‘routes->web.php’ file, add the following line of code.

Route::get('/', 'DataController@index'); Route::get('downloadData/{type}', 'DataController@downloadData'); Route::post('importData', 'DataController@importData');
Code language: PHP (php)
  1. Create the view File

Create index.blade.php in resources/views folder and add the following code.

resources/views/index.blade.php

<html lang="en"> <head> <title>Laravel Import Export to Excel , CSV Example - bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <style> .container{ margin-top: 10%; } </style> <body> <div class="container"> @if ($errors->any()) <div class="alert alert-danger"> <a href="#" class="close" data-dismiss="alert" aria-label="close">Γ—</a> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @if (Session::has('success')) <div class="alert alert-success"> <a href="#" class="close" data-dismiss="alert" aria-label="close">Γ—</a> <p>{{ Session::get('success') }}</p> </div> @endif <div class="card"> <div class="card-body"> <h5 class="card-title">Laravel Import Export to Excel , CSV Example</h5> <a href="{{ url('downloadData/xlsx') }}"><button class="btn btn-dark">Download Excel xlsx</button></a> <a href="{{ url('downloadData/xls') }}"><button class="btn btn-success">Download Excel xls</button></a> <a href="{{ url('downloadData/csv') }}"><button class="btn btn-info">Download CSV</button></a> <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;" action="{{ url('importData') }}" class="form-horizontal" method="post" enctype="multipart/form-data"> @csrf <input type="file" name="import_file" /> <button class="btn btn-primary">Import File</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Facebook Login with Socialite in Laravel 5.8

The tutorial is created to implement facebook login using Socialite in Laravel 6.0, 5.8 , 5.7 and 5.6. Using Facebook Auth to log and register into your Laravel Application. Follow the steps below to implement laravel socialite facebook login.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel facebookAuth
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=mysql DB_HOST='Your DB Host' DB_PORT='Your DB Port' DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Add Socialite

Go to the terminal and type the following php artisan command to download Socialite Package.

composer require laravel/socialite
Code language: JavaScript (javascript)

After installing the package , Configure the provider and aliases in “config/app.php”. Edit the file with the code below.

config/app.php

'providers' => [ // Other service providers… Laravel\Socialite\SocialiteServiceProvider::class, ], 'aliases' => [ // Other aliases… 'Socialite' => Laravel\Socialite\Facades\Socialite::class, ],
Code language: PHP (php)
  1. Get Secret id and key from Facebook Developer Console

In this step, Configure the CLIENT ID and CLIENT SECRET to add facebook a authentication to your laravel project, Lets begin by opening Developer Console and then create a new App by submitting the name and email.

Developer Console
Developer Console

After creating the App, go to Setting->Advanced and set redirect url as shown below.

Developer Console URL
Developer Console URL

Now it’s time to add Facebook Login by navigating to products in the left menu.

Developer Console Product
Developer Console Product

In this Step, Specify Auth redirect url facebook login->setting and set valid auth redirect url.

Developer Console Auth
Developer Console Auth

After successfully configuring the app on facebook developer console, Set the client id and client secret in config/service.php as shown below

config/service.php

'facebook' => [ 'client_id' => 'xxxx', 'client_secret' => 'xxx', 'redirect' => 'https://bishrulhaq.com/callback/facebook', ],
Code language: PHP (php)
  1. Create route, controller and model

In this step, Go to app/User.php file and add the following line of code.

app/User.php

protected $fillable = ['name', 'email', 'password', 'provider', 'provider_id' ];
Code language: PHP (php)

In this step, Go to app/database/create_users_table.php and add the code below

app/database/create_users_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique()->nullable(); $table->string('provider'); $table->string('provider_id'); $table->timestamp('email_verified_at')->nullable(); $table->string('password')->nullable(); $table->rememberToken()->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
Code language: HTML, XML (xml)

Now it’s time to run Laravel Default Auth by typing the command at your terminal.

php artisan make:auth
Code language: CSS (css)

Next, You need to type the following command to run the migration.

php artisan migrate

If you encounter any errors while migrating the table. Add String length under boot method at app/providers/AppServiceProvider.php file and re-run the migration.

use Illuminate\Support\Facades\Schema; function boot() { Schema::defaultStringLength(191); }
Code language: CSS (css)

In this step, Go to ‘routes->web.php’ file, add the following line of code.

routes->web.php

Route::get('/auth/redirect/{provider}', 'AuthController@redirect'); Route::get('/callback/{provider}', 'AuthController@callback');
Code language: PHP (php)

Create AuthController by typing the following command.

php artisan make:controller AuthController
Code language: CSS (css)
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator, Redirect, Response, File; use Socialite; use App\User; class AuthController extends Controller { public function redirect($provider) { return Socialite::driver($provider)->redirect(); } public function callback($provider) { $getInfo = Socialite::driver($provider)->user(); $user = $this->createUser($getInfo, $provider); auth()->login($user); return redirect()->to('/home'); } function createUser($getInfo, $provider) { $user = User::where('provider_id', $getInfo->id)->first(); if (!$user) { $user = User::create([ 'name' => $getInfo->name, 'email' => $getInfo->email, 'provider' => $provider, 'provider_id' => $getInfo->id ]); } return $user; } }
Code language: HTML, XML (xml)
  1. Edit the View

Go to Resources/Views/Auth/login.blade.php and add facebook social login button under the login area.

Resources/Views/Auth/login.blade.php

<hr> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <a href="{{ url('/auth/redirect/facebook') }}" class="btn btn-primary"><i class="fa fa-facebook"></i> Facebook</a> </div> </div>
Code language: HTML, XML (xml)

Finally, Laravel Facebook Auth Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Laravel 5.8 Form Request Validation

There are plenty of validation methods available to validate the form data request with Laravel 5.8. By default Laravel’s base controller class uses a ValidatesRequests trait which provides a way to validate incoming HTTP request with many validation rules.

# Form Request Validation

For more complex validation scenarios, you may wish to create a “form request”. Form requests are custom request classes that contain validation logic. Refer more aboutΒ form request validationΒ to see from the Laravel 5.8 Documentation.

In this tutorial, You’ll learn to implement validation for Form Request. Follow the step by step guide to create the application.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel formRequestValidation
  1. Configure Database Details

You need to create the database at MYSQL and then we need to connect that database to the Laravel project (You can also use phpmyadmin to create the database). Open the .env file inside Laravel project and add the database credentials as below

.env

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE='Your DB Name' DB_USERNAME='Your DB UserName' DB_PASSWORD='Your DB Password'
Code language: JavaScript (javascript)
  1. Create Form Requests

Form requests are used to create custom validation logics. To create a form request class type the command in your terminal as below.

php artisan make:request FormDataRequest
Code language: CSS (css)

The generated class will be stored in in the app/Http/Requests file directory. Open FormDataRequest.php from the directory and add the validation rules inside the rules method and the custom messages inside the messages method.

app\Http\Requests\FormDataRequest.php

<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class FormDataRequest extends FormRequest { public function authorize() { return true; } public function messages() { return [ 'name.required' => 'The name is Required.', 'detail.required' => 'The detail is Required.', 'price.required' => 'The price is Required.', ]; } public function rules() { return [ 'name' => 'bail|required|max:255', 'detail' => 'required|max:255', 'price' => 'required|numeric', ]; } }
Code language: HTML, XML (xml)

Now, You need to return true; from the authorize() method. If the authorize method returns false, a HTTP response with a 403 status code will be returned.

public function authorize() { return true; }
Code language: PHP (php)
  1. Create the migration file.

Type the following command at your terminal to create the model and migration files.

php artisan make:migration create_form_data_table --create=formData

The migration will be created under “database/migrations”. Edit the file with the code below to create formData Table.

create_form_data_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFormDataTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('formData', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('detail'); $table->integer('price'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('formData'); } }
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate

Create the FormData model using the following command.

php artisan make:model FormData
Code language: CSS (css)

The model wil be generated in “app/FormData.php” Now, we will write the schema inside FormData.php file.

app/FormData.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class FormData extends Model { protected $table = 'formData'; protected $fillable = ['name', 'detail', 'price']; }
Code language: HTML, XML (xml)
  1. Create FormDataController

Type the following command at your terminal to create FormDataController.php file in controllers

php artisan make:controller FormDataController
Code language: CSS (css)

app/Http/Controllers/FormDataController.php

<?php namespace App\Http\Controllers; use App\FormData; use App\Http\Requests\FormDataRequest; class FormDataController extends Controller { public function index() { return view('index'); } public function save(FormDataRequest $request) { $validatedData = $request->validated(); FormData::create($validatedData); return redirect()->back()->with('success', 'The Form Data is successfully inserted to the Database!'); } }
Code language: HTML, XML (xml)

Now, write the two routes in routes -> web.php file.

Route::get('/', 'FormDataController@index')->name('form.index'); Route::post('form', 'FormDataController@save')->name('form.save');
Code language: PHP (php)
  1. Create the view Files

create the following five files inside resources -> views folder.

  1. layout.blade.php
  2. index.blade.php

resources/views/layout.blade.php

<!DOCTYPE html> <html> <head> <title>Laravel 5.8 Form Request Validation Application - bishrulhaq.com</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row" style="margin-top: 20px;"> <div class="col-12"> @yield('content') </div> </div> </div> </body> </html>
Code language: HTML, XML (xml)

resources/views/index.blade.php

@extends('layout') @section('content') <div class="card"> <div class="card-header"> Insert Data </div> <div class="card-body"> @if(session()->has('success')) <div class="alert alert-success"> {{ session()->get('success') }} </div> @endif @if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form method="post" action="{{ route('form.save') }}"> <div class="form-group"> @csrf <label for="name">Name : </label> <input type="text" class="form-control" name="name"/> </div> <div class="form-group"> <label for="price">Detail : </label> <input type="text" class="form-control" name="detail"/> </div> <div class="form-group"> <label for="quantity">Price : </label> <input type="text" class="form-control" name="price"/> </div> <button type="submit" class="btn btn-primary">Save Data</button> </form> </div> </div> @endsection
Code language: HTML, XML (xml)

Finally, Laravel 5.8 Form Request Validation Application is ready to run. Type the following command in your terminal to run the application.

php artisan serve

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

How to build an API with Laravel 5.8 using Sqlite

This tutorial focuses on setting up REST API in Laravel 5.8 using PHPUnit and SQLITE. If you’re new to Laravel or PHPUnit, Check out the Laravel Getting Started Guide and PHPUnit Documentation for more information.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel restApiApplication
  1. Install & Configure Database

You need to create the database as SQLite and then we need to connect that database to the Laravel project. Create the sqlite file named database.sqlite under database folder as shown below.

database/database.sqlite

Open the .env file inside Laravel project and add the database credentials as below.

.env

DB_CONNECTION=sqlite DB_DATABASE='project_path'/database/database.sqlite
Code language: JavaScript (javascript)
  1. Create a database model, migration

In this step, we’re going to create a Data model with a few options:

php artisan make:model Data --migration
Code language: CSS (css)

The migration will be created under “database/migrations”. Edit the file with the code below to create Data Table.

‘date’_create_data_table.php

<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDataTable extends Migration { public function up() { Schema::create('data', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('data'); } }
Code language: HTML, XML (xml)

Type the following command to run the migration.

php artisan migrate

Open the generated model in “app/Data.php” Now, Write the schema inside Data.php file.

app/Data.php

<?php namespace App; use Illuminate\Database\Eloquent\Model; class Data extends Model { protected $fillable = ['title','description']; }
Code language: HTML, XML (xml)
  1. Create DataController

Type the following command at your terminal to create DataController.php file in controllers

php artisan make:controller DataController --resource.
Code language: CSS (css)

app/Http/Controllers/DataController.php

<?php namespace App\Http\Controllers; use App\Data; use Illuminate\Http\Request; class DataController extends Controller { public function index() { $data = Data::all(); return response()->json($data); } public function store(Request $request) { $request->validate([ 'title' => 'required', 'description' => 'required' ]); $data = Data::create($request->all()); return response()->json([ 'message' => 'Data Successfully Stored!', 'data' => $data ]); } public function show(Request $request) { $data = Data::where('id' , '=' , $request->id)->first(); return response()->json([ 'message' => 'Fetching Data!', 'data' => $data ]); } public function update(Request $request, Data $data) { $request->validate([ 'title' => 'nullable', 'description' => 'nullable' ]); $data->update($request->all()); return response()->json([ 'message' => 'Great success! Task updated', ]); } public function destroy(Data $data) { $data->delete(); return response()->json([ 'message' => 'Data Successfully deleted!' ]); } }
Code language: HTML, XML (xml)

Now, write the routes in routes -> api.php file.

Route::get('/data', 'DataController@index')->name('path.index'); Route::post('/data', 'DataController@store')->name('path.store'); Route::get('/data/{id}', 'DataController@show')->name('path.show'); Route::put('/data/{data}', 'DataController@update')->name('path.update'); Route::delete('/data/{data}', 'DataController@destroy')->name('path.destroy');
Code language: PHP (php)
  1. Creating & Running Tests

Create the test by typing the command below in your terminal.

php artisan make:test DataTest
Code language: CSS (css)

Open phpunit.xml at your project folder and add the following lines about the testing database at the bottom of phpunit.xml. This specifies connecting to a SQLite database for testing that’s stored in memory.

..... <php> <env name="APP_ENV" value="testing"/> <env name="BCRYPT_ROUNDS" value="4"/> <env name="CACHE_DRIVER" value="array"/> <env name="MAIL_DRIVER" value="array"/> <env name="QUEUE_CONNECTION" value="sync"/> <env name="SESSION_DRIVER" value="array"/> <env name="DB_CONNECTION" value="sqlite"/> <env name="DB_DATABASE" value=":memory:"/> </php> </phpunit>
Code language: HTML, XML (xml)
  1. Create a factory

To simplify creating data, we can use Factories. These Factories are used to insert a few records into the database before running tests. Instead of manually inserting the values of each column to the database.

Type the following command in your terminal to create the factory.

php artisan make:factory DataFactory --model=Data

The factories are located in the database/factories folder. Paste the following code in DataFactory.php

database/factories/DataFactory.php

<?php use App\Data; use Faker\Generator as Faker; $factory->define(Data::class, function (Faker $faker) { return [ 'title' => $faker->sentence(), 'description' => $faker->text() ]; });
Code language: HTML, XML (xml)
  1. Create the Test functions

Inside the test, We need to specify the DatabaseMigrations in tests/Feature folder to set up testing database from the migration files before the first test run.

test/Feature/DataTest.php

<?php namespace Tests\Feature; use App\Data; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class DataTest extends TestCase { use RefreshDatabase; /** @test */ public function show_all_data() { factory(Data::class, 10)->create(); $response = $this->json('GET', route('path.index')); $response->assertStatus(200); $response->json(); /* Uncomment to view Response */ //print_r($response->json()); } /** @test */ public function create_data() { $response = $this->json('POST', route('path.store'), [ 'title' => 'Dummy title', 'description' => 'Dummy description' ]); $response->assertStatus(200); $this->assertEquals('Dummy title',$response->json()['data']['title']); /* Uncomment to show Response */ //print_r($response->json()); } /** @test */ public function show_specific_data() { $this->json('POST', route('path.store'), [ 'title' => 'Dummy title', 'description' => 'Dummy description' ]); $data = Data::all()->first(); $response = $this->json('GET', route('path.show',$data->id)); $response->assertStatus(200); $response->json(); /* Uncomment to show Response */ //print_r($response->json()); } /** @test */ public function update_data() { $this->json('POST', route('path.store'), [ 'title' => 'Dummy title', 'description' => 'Dummy description' ]); $data = Data::all()->first(); $response = $this->json('PUT', route('path.show',$data->id),['title' => 'Dummy updated title']); $response->assertStatus(200); $response->json(); /* Uncomment to show Response */ //print_r($response->json()); } /** @test */ public function delete_data() { $this->json('POST', route('path.store'), [ 'title' => 'Dummy title', 'description' => 'Dummy description' ]); $data = Data::all()->first(); $response = $this->json('DELETE', route('path.destroy', $data->id)); $response->assertStatus(200); $response->json(); /* Uncomment to show Response */ //print_r($response->json()); } }
Code language: HTML, XML (xml)

Finally, You are ready to run your Laravel 5.8 API. Type the following command in your terminal to run the tests.

vendor\bin\phpunit

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Laravel Cheat Sheet for Eloquent ORM

ORM (Object-relational mapping) is used to make database CRUD operations easier. Laravel comes with Eloquent ORM. This tutorial is created to provide some of the frequently used cheat sheet for Laravel Eloquent ORM

  1. Ordering Eloquent hasMany() relationship

Add ->orderBy() to the hasMany relationship to get ordered output of a specified column.

return $this->hasMany('Detail::class')->orderBy('column');
Code language: PHP (php)
  1. Eloquent’s where() method

Here are some useful cheat sheet for eloquent’s where() method.

$detail = Detail::where("id","!=",50)->get(); // Any of the following may be used as the second parameter (and use the third param for the value) // =, <, >, <=, >=, <>, !=, LIKE, NOT LIKE, BETWEEN, ILIKE $detail = Detail::where(function ($query) { $query->where('a', '=', 1) ->orWhere('b', '=', 1); })->get(); $detail = Detail::whereRaw('age > ? and votes = 100', array(25))->get(); $detail = Detail::whereRaw(DB::raw("id in (select detail_id from students GROUP BY students.detail_id)"))->get(); $detail = Detail::whereExists(function($query){ $query->select(DB::raw(1)) ->from('students') ->whereRaw('students.detail_id = details.id') ->groupBy('students.detail_id') ->havingRaw("COUNT(*) > 0"); })->get(); // Any of the following may be used instead of Detail::whereExists // ->orWhereExists(), ->whereNotExists(), ->orWhereNotExists() $detail = Detail::whereIn('column',[1,2,3])->get(); // Any of the following may be used instead of Detail::whereExists // ->orWhereIn(), $detail = Detail::whereNotIn('id', function($query){ $query->select('student_id') ->from('students') ->groupBy('students.student_id'); })->get(); // Any of the following may be used instead of Detail::whereExists // ->whereNotIn(), ->orWhereNotIn
Code language: PHP (php)

Here are some more useful cheat sheet for NULL or NOT NULL in laravel eloquent.

->whereNull('column') ->orWhereNull('column') ->whereNotNull('column') ->orWhereNotNull('column')
Code language: PHP (php)

Cheat sheet to filter by Day, Month, Year, Date options.

->whereDay() ->whereMonth('column', '=', 1) ->whereYear('column', '>', 2019) ->whereDate('column', '>', '2019-05-05')
Code language: PHP (php)
  1. Prevent Eloquent from adding created_at or updated_at timestamps

Disable both created_at and updated_at in the model to disable the timestamps

const UPDATED_AT = null; const CREATED_AT = null;
Code language: JavaScript (javascript)

Make sure to remove this from the migration

$table->timestamps()
Code language: PHP (php)
  1. restore() soft deleted Eloquent

Use the restore() method to undelete a record.

User::withTrashed()->where("id",1)->restore()
Code language: PHP (php)

Make sure to add following lines in the model to enable SoftDeletes.

use SoftDeletes;
Code language: PHP (php)
  1. Joins in Eloquent

Here are some useful cheat sheet for eloquent’s join() method.

$product = Product:where('id', $productId) ->join('businesses','product.business_id','=','businesses.id') ->select('product.id','businesses.name')->first(); $product = Product:where('id', $productId) ->leftJoin('businesses','product.business_id', '=', 'businesses.id') ->select('product.id','businesses.name')->first(); $product = Product:where('id', $productId) ->join('businesses',function($join) use($cats) { $join->on('product.business_id', '=', 'businesses.id') ->on('product.id', '=', $cats, 'and', true);})->first();
Code language: PHP (php)
  1. Find an item by Primary Key in Eloquent, or throw a ModelNotFoundException

findOrFail($id) method will find a model by it’s primary key or throw an exception if it’s not available.

$id = 10001; $user = User::findOrFail($id);
Code language: PHP (php)
  1. Cache in Eloquent

You can retrieve an item from the cache without loading it all the item.

$details = Cache::remember('details', $seconds, function () { return DB::table('details')->get(); });
Code language: PHP (php)

rememberForever method is used to retrieve an item from the cache or store it forever

$details = Cache::rememberForever('details', function () { return DB::table('details')->get(); });
Code language: PHP (php)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
PHP

Simple PHP Page Router

This is a simple yet basic PHP routing application created to direct all request to index.php and route the files to it’s relevant paths.

  1. Create the Configuration file

In the root directory, Specify the configuration by creating a .htaccess file to redirect all requests to index.php.

.htaccess

RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+)$ index.php [QSA,L]
  1. Create the Router

Specify the pages you want to redirect by adding the url in the switch statement. It will redirect to your specified file and if the url is not available then it’ll redirect to the default case.

index.php

<?php $redirect = $_SERVER['REQUEST_URI']; // You can also use $_SERVER['REDIRECT_URL']; switch ($redirect) { case '/' : case '' : require __DIR__ . '/pages/home.php'; break; case '/contact' : require __DIR__ . '/pages/contact.php'; break; default: require __DIR__ . '/pages/404.php'; break; }
Code language: HTML, XML (xml)
  1. Create the Pages

Create the following home.phpcontact.php404.php files under pages directory and copy the below codes to each files.

pages/home.php

<h1>Home</h1>
Code language: HTML, XML (xml)

pages/contact.php

<h1>Contact</h1>
Code language: HTML, XML (xml)

pages/404.php

<h1>Error! Page Not Found.</h1>
Code language: HTML, XML (xml)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
Laravel

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically. Cron is a task scheduler daemon which is used to run scheduled tasks at specific intervals. Cron uses the configuration file called Crontab, also known as cron table, to manage the scheduling process.

# Laravel 5.8

Laravel 5.8 continues the improvements made in the previous release (version 5.7). ReferΒ release notesΒ to see the changes made in Laravel 5.8.

In this tutorial, You’ll learn to implement Cron Jobs to schedule tasks in Laravel 5.8. Follow the step by step guide to create the Cron Job.

  1. Install Laravel 5.8

First, let install Laravel 5.8 using the following command (Make sure you have installed composer in your PC). Click on Install Composer If you haven’t installed Composer on your PC.

composer create-project --prefer-dist laravel/laravel dummyCron
  1. Create the Custom Command

In this step, You need to create the custom command class by typing the following command in your terminal.

php artisan make:command DummyCron --command=dummy:cron

The cron job will be created under “app/Console/Commands/”. Edit the file with the code below to implement the logic.

app/Console/Commands/DemoCron.php

<?php namespace App\Console\Commands; use Illuminate\Console\Command; class DummyCron extends Command { protected $signature = 'dummy:cron'; protected $description = 'Dummy Cron Job Application'; public function __construct() { parent::__construct(); } public function handle() { \Log::info("Running!"); } }
Code language: HTML, XML (xml)
  1. Register the Custom Command

After successfully creating DemoCron.php file, we need to register this command in kernel.php file with task scheduling as seen below,

$schedule->command(‘dummy:cron’) is where we define what command needs to be executed and ->everyMinute(); defines the frequency of execution. There are more time intervals that we can define. You can find more about Task Scheduling in Laravel Documentation. Some of the Schedule Frequency Options as below,

Method Description
->everyMinute(); Run the task every minute
->everyFiveMinutes(); Run the task every five minutes
->hourly(); Run the task every hour
->daily(); Run the task every day at midnight
->weekly(); Run the task every week

app/Console/Kernel.php

<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { protected $commands = [ Commands\DummyCron::class, ]; protected function schedule(Schedule $schedule) { $schedule->command('dummy:cron')->everyMinute(); } protected function commands() { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } }
Code language: HTML, XML (xml)
  1. Run Scheduler Command on Localhost

In this step, Run the below command to test the CRON Job at your localhost.

php artisan schedule:run
Code language: CSS (css)

After running the above command, You’ll get the output in your Log file as below.

[1994-08-01 01:10:42] local.INFO: Running! [1994-08-01 01:10:43] local.INFO: Running! [1994-08-01 01:10:44] local.INFO: Running!
Code language: CSS (css)
  1. Run Scheduler Command on Live Server

Type the following command at your project directory to run Cron Job at your Live Server

php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
Code language: JavaScript (javascript)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Categories
PHP

Convert PHP Array To JSON : Examples

This tutorial focuses on converting PHP Array to JSON. It is used to read data from the server and display it to the Web. JSON is a text format , and We can convert any JS Object into a JSON format.

  1. Covert PHP array to JSON

PHP is capable of handling JSON and it has some built-in functions to handle them. json_encode() is used to convert objects, arrays in PHP to JSON format. The PHP json_encode() function returns the string containing a JSON equivalent of the value passed.

The syntax of json_encode() function as following.

json_encode(value, options)

Here’s how we need to convert the numerically indexed array into JSON

<?php $names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer']; $namesJSON = json_encode($names); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :["Bishrul","Bishrul Haq","Developer","Software Engineer"]
Code language: JavaScript (javascript)

If you want the array to be output as Object , you can use JSON_FORCE_OBJECT option as below,

<?php $names = ['Bishrul', 'Bishrul Haq', 'Developer', 'Software Engineer']; $namesJSON = json_encode($names,JSON_FORCE_OBJECT); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :{"0":"Bishrul","1":"Bishrul Haq","2":"Developer","3":"Software Engineer"}
Code language: JavaScript (javascript)
  1. Convert PHP Associative Array to JSON

To Convert a key-value pair array (Associative Array), you can also use json_encode() to convert objects, arrays in PHP to JSON format.

Here’s how we need to convert an associative array into JSON

<?php $names = ['Name'=>'Bishrul', 'Full Name'=>'Bishrul Haq', 'Details'=>'Developer', 'Designation'=>'Software Engineer']; $namesJSON = json_encode($names); echo "Names in JSON :".$namesJSON;
Code language: HTML, XML (xml)

Output :

Names in JSON :{"Name":"Bishrul","Full Name":"Bishrul Haq","Details":"Developer","Designation":"Software Engineer"}
Code language: JavaScript (javascript)

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.