Build your own URL shortener using Laravel

Build your own URL shortener using Laravel

In this article, you'll learn how to generate short url in laravel application.

Sometime we need to make shorten url string instead of long url. In this tutorial i will show you step by step how to create shorten a url in Laravel 5 without any package. You can write your own script function for generator short link in Laravel.

If you are working with SMS or some where share with limited character and at that time if you need to share any url or link then you must have to generate shortener url. In your project it's need many times then you must have to implement module that can help to generate url shortener with your website domain.

You need to just follow step by step this tutorial, you will get very simple module for generate short link in Laravel 5. I will also give you free download whole script.

Step 1: Install Laravel 5

In this step, if you haven't Laravel 5 application setup then we have to get fresh Laravel 5 application. So run bellow command and get clean fresh laravel 5 application.

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

Step 2: Create Table

we are going to create from scratch application for create short link. so we have to create migration for "short_links" table using Laravel 5.8 php artisan command, so first fire bellow command:

php artisan make:migration create_short_links_table

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create short_links table.

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class CreateShortLinksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('short_links', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('code');
            $table->string('link');
            $table->timestamps();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('short_links');
    }
}

Now you have to run this migration by following command:

php artisan migrate

Step 3: Create Model

In this step, now we should create new model as ShortLink. So run bellow command and create new model. run bellow command:

php artisan make:model ShortLink

app/ShortLink.php

<?php
   
namespace App;
   
use Illuminate\Database\Eloquent\Model;
   
class ShortLink extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'code', 'link'
    ];
}

Step 4: Create Route

In this is step we need to create route for layout file and another one for store data. so open your routes/web.php file and add following route.

routes/web.php

Route::get('generate-shorten-link', '[email protected]');
Route::post('generate-shorten-link', '[email protected]')->name('generate.shorten.link.post');
   
Route::get('{code}', '[email protected]')->name('shorten.link');

Step 5: Create Controller

In this point, now we should create new controller as ShortLinkController. this controller will manage layout and store data to database, so put bellow content in controller file:

app/Http/Controllers/ShortLinkController.php

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\ShortLink;
  
class ShortLinkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $shortLinks = ShortLink::latest()->get();
   
        return view('shortenLink', compact('shortLinks'));
    }
     
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
           'link' => 'required|url'
        ]);
   
        $input['link'] = $request->link;
        $input['code'] = str_random(6);
   
        ShortLink::create($input);
  
        return redirect('generate-shorten-link')
             ->with('success', 'Shorten Link Generated Successfully!');
    }
   
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function shortenLink($code)
    {
        $find = ShortLink::where('code', $code)->first();
   
        return redirect($find->link);
    }
}

Step 6: Create View

In Last step, let's create shortenLink.blade.php(resources/views/shortenLink.blade.php) for layout and we will write design code here and put following code:

resources/views/shortenLink.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to create url shortener using Laravel? - ItSolutionStuff.com</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
   
<div class="container">
    <h1>How to create url shortener using Laravel? - ItSolutionStuff.com</h1>
   
    <div class="card">
      <div class="card-header">
        <form method="POST" action="{{ route('generate.shorten.link.post') }}">
            @csrf
            <div class="input-group mb-3">
              <input type="text" name="link" class="form-control" placeholder="Enter URL" aria-label="Recipient's username" aria-describedby="basic-addon2">
              <div class="input-group-append">
                <button class="btn btn-success" type="submit">Generate Shorten Link</button>
              </div>
            </div>
        </form>
      </div>
      <div class="card-body">
   
            @if (Session::has('success'))
                <div class="alert alert-success">
                    <p>{{ Session::get('success') }}</p>
                </div>
            @endif
   
            <table class="table table-bordered table-sm">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Short Link</th>
                        <th>Link</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($shortLinks as $row)
                        <tr>
                            <td>{{ $row->id }}</td>
                            <td><a href="{{ route('shorten.link', $row->code) }}" target="_blank">{{ route('shorten.link', $row->code) }}</a></td>
                            <td>{{ $row->link }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
      </div>
    </div>
   
</div>
    
</body>
</html>

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow url on your browser:

http://localhost:8000/generate-shorten-link

You can download whole code from here

Laravel 5.8 Tutorial: Build your First CRUD App with Laravel and MySQL (PHP 7.1+)

Laravel 5.8 Tutorial: Build your First CRUD App with Laravel and MySQL (PHP 7.1+)

Laravel 5.8 Tutorial: Build your First CRUD App with Laravel and MySQL (PHP 7.1+)

Originally published at techiediaries.com on 12 Mar 2019

Throughout this tutorial for beginners you'll learn to use Laravel 5.8 - the latest version of one of the most popular PHP frameworks - to create a CRUD web application with a MySQL database from scratch and step by step starting with the installation of Composer (PHP package manager) to implementing and serving your application.

Note: Laravel 5.8 is recently released and this tutorial is upgraded to the latest version.
Also read: Laravel 5.8 REST CRUD API Tutorial - Build a CRM [PART 1]: Eloquent Models and Relationships
Laravel 5.8 New Features

Let's start our tutorial by going through the most important features introduced in this version.

  • The hasOneThrough Eloquent relationship.
  • Better email validation,
  • Auto-Discovery Of Model Policies provided that the model and policy follow standard Laravel naming conventions
  • DynamoDB cache and session drivers,
  • Added support for PHPUnit 8.0 for unit testing,
  • Added support for Carbon 2.0, an easy to use PHP API extension for DateTime,
  • Added support Pheanstalk 4.0: a pure PHP 5.3+ client for the beanstalkd workqueue, etc.

The Laravel 5.8 version has also corrected numeroous bugs and introduced many improvements of the Artisan CLI.

Check out the official docs for details features of Laravel 5.8

Prerequisites

This tutorial assumes you have PHP and MySQL installed on your system. Follow the instructions for your operating system to install both of them.

You also need to be familiar with Linux/macOS bash where we'll be executing the commands in this tutorial.

Familiarly with PHP is required since Laravel is based on PHP.

For development I will be using a Ubuntu 16.04 machine so the commands in this tutorial are targeting this system but you should be able to follow this tutorial in any operating system you use.

Installing PHP 7.1

Laravel v5.8 requires PHP 7.1 or above so you need the latest version of PHP installed on your system. The process is straightforward on most systems.

On Ubuntu, you can follow these instructions.

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

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

Next, install PHP 7.1 using the following command:

$ sudo apt-get install php7.1

If you are using Ubuntu 18.04, PHP 7.2 is included in the default Ubuntu repository for 18.04 so you should be able to install it using the following command:

$ sudo apt-get install php
This tutorial is tested with PHP 7.1 but you can also use more recent versions like PHP 7.2 or PHP 7.3

Installing the Required PHP 7.1 Modules

Laravel requires a bunch of modules. You can install them using the following command:

$ sudo apt-get install php7.1 php7.1-cli php7.1-common php7.1-json php7.1-opcache php7.1-mysql php7.1-mbstring php7.1-mcrypt php7.1-zip php7.1-fpm php7.1-xml
Installing PHP Composer

Let's start our journey by install Composer, The PHP package manager.

Navigate in your home directory, then download the installer from the official website using curl:

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

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

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

As of this writing Composer 1.8 will be installed on your system. You can make sure your installation works as expected by running composer in your terminal:

$ composer

You should get the following output:

   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.8.0 2018-12-03 10:31:16

Usage:
command [options] [arguments]

Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--profile Display timing and memory usage information
--no-plugins Whether to disable plugins.
-d, --working-dir=WORKING-DIR If specified, use the given directory as working directory.
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

For more information check out this tutorial.

If you've successfully installed Composer in your system, you are ready to create a Laravel 5.8 project.

Installing and Creating a Laravel 5.8 Project

In this section we'll introduce Laravel and then proceed it to install and create a Laravel 5.8 project.

About Laravel

Laravel docs describe it as:

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:
  • Simple, fast routing engine.
  • Powerful dependency injection container.
  • Multiple back-ends for session and cache storage.
  • Expressive, intuitive database ORM.
  • Database agnostic schema migrations.
  • Robust background job processing.
  • Real-time event broadcasting.
Laravel is accessible, yet powerful, providing tools needed for large, robust applications.

Generating a Laravel 5.8 project is easy and straightforward. In your terminal, run the following command:

$ composer create-project  --prefer-dist  laravel/laravel laravel-first-crud-app

This will install laravel/laravel v5.8.3.

Note: Make sure you have PHP 7.1 installed on your system. Otherwise, composer will use Laravel 5.5 for your project.

You can verify the installed version in your project using:

$ cd laravel-first-crud-app
$ php artisan -V
Laravel Framework 5.8.19
Installing the Front-End Dependencies

In your generated project, you can see that a package.json file is generated which includes many front-end libraries that can be used by your project:

  • axios,
  • bootstrap,
  • cross-env,
  • jquery,
  • laravel-mix,
  • lodash,
  • popper.js,
  • resolve-url-loader,
  • sass,
  • sass-loader,
  • vue.
Note: You can use your preferred libraries with Laravel not specifically the ones added to package.json.
The package.json file in your Laravel project includes a few packages such as vue and axios to help you get started building your JavaScript application.
It also includes bootstrap to help you get started with Bootstrap for styling your UI.
It include Laravel Mix to help you compile your SASS files to plain CSS.

You need to use npm to install the front-end dependencies:

$ npm install

After running this command a node_modules folder will be created and the dependencies will be installed into it.

Note: You need to have Node.js and npm installed on your system before you can install the front-end dependencies.
Creating a MySQL Database

Let's now create a MySQL database that we'll use to persist dat ain our Laravel application. In your terminal, run the following command to run the mysql client:

$ mysql -u root -p

When prompted, enter the password for your MySQL server when you've installed it.

Next, run the following SQL statement to create a db database:

mysql> create database db;

Open the .env file and update the credentials to access your MySQL database:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db
DB_USERNAME=root
DB_PASSWORD=******

You need to enter the database name, the username and password.

At this point, you can run the migrate command to create your database and a bunch of SQL tables needed by Laravel:

$ php artisan migrate
Note: You can run the migrate command at any other points of your development to add other SQL tables in your database or to later your database if you need to add any changes later.
Creating your First Laravel Model

Laravel uses the MVC architectural pattern to organize your application in three decoupled parts:

  • The Model which encapsulates the data access layer,
  • The View which encapsulates the representation layer,
  • Controller which encapsulates the code to control the application and communicates with the model and view layers.

Wikipedia defines MVC as:

Model–view–controller is an architectural pattern commonly used for developing user interfacesthat divides an application into three interconnected parts. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.

Now, let's create our first Laravel Model. In your terminal, run the following command:

$ php artisan make:model Contact --migration

This will create a Contact model and a migration file. In the terminal, we get an output similar to:

Model created successfully.
Created Migration: 2019_01_27_193840_create_contacts_table

Open the database/migrations/xxxxxx_create_contacts_table migration file and update it accordingly:

<?php

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

class CreateContactsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('first_name');
$table->string('last_name');
$table->string('email');
$table->string('job_title');
$table->string('city');
$table->string('country');
});
}

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

}

We added the first_namelast_nameemailjob_titlecity and country fields in the contacts table.

You can now create the contacts table in the database using the following command:

$ php artisan migrate

Now, let's look at our Contact model, which will be used to interact with the contacts database table. Open the app/Contact.php and update it:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
protected $fillable = [
'first_name',
'last_name',
'email',
'city',
'country',
'job_title'
];
}

Creating the Controller and Routes

After creating the model and migrated our database. Let's now create the controller and the routes for working with the Contact model. In your terminal, run the following command:

$ php artisan make:controller ContactController --resource
Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for "photos" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:
This command will generate a controller at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations.

Open the app/Http/Controllers/ContactController.php file. This is the initial content:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

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

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

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

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

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

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

}

The ContactController class extends Controller class available from Laravel and defines a bunch of methods which will be used to do the CRUD operations against the Contact model.

You can read the role of the method on the comment above it.

Now we need to provide implementations for these methods.

But before that, let's add routing. Open the routes/web.php file and update it accordingly:

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

Route::resource('contacts', 'ContactController');

Using the resource() static method of Route, you can create multiple routes to expose multiple actions on the resource.

These routes are mapped to various ContactController methods which will need to implement in the next section:

  • GET/contacts, mapped to the index() method,
  • GET /contacts/create, mapped to the create() method,
  • POST /contacts, mapped to the store() method,
  • GET /contacts/{contact}, mapped to the show() method,
  • GET /contacts/{contact}/edit, mapped to the edit() method,
  • PUT/PATCH /contacts/{contact}, mapped to the update() method,
  • DELETE /contacts/{contact}, mapped to the destroy() method.

These routes are used to serve HTML templates and also as API endpoints for working with the Contactmodel.

Note: If you want to create a controller that will only expose a RESTful API, you can use the apiResource method to exclude the routes that are used to serve the HTML templates:
Route::apiResource('contacts', 'ContactController');
Implementing the CRUD Operations

Let's now implement the controller methods alongside the views.

C: Implementing the Create Operation and Adding a Form

The ContactController includes the store() method that maps to the POST /contacts API endpoint which will be used to create a contact in the database and the create() that maps to the GET /contacts/create route which will be used to serve the HTML form used to submit the contact to POST /contacts API endpoint.

Let's implement these two methods.

Re-open the app/Http/Controllers/ContactController.php file and start by importing the Contactmodel:

use App\Contact;

Next, locate the store() method and update it accordingly:

    public function store(Request $request)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);

    $contact = new Contact([
        'first_name' =&gt; $request-&gt;get('first_name'),
        'last_name' =&gt; $request-&gt;get('last_name'),
        'email' =&gt; $request-&gt;get('email'),
        'job_title' =&gt; $request-&gt;get('job_title'),
        'city' =&gt; $request-&gt;get('city'),
        'country' =&gt; $request-&gt;get('country')
    ]);
    $contact-&gt;save();
    return redirect('/contacts')-&gt;with('success', 'Contact saved!');
}

Next, locate the create() method and update it:

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

The create() function makes use of the view() method to return the create.blade.php template which needs to be present in the resources/views folder.

Before creating the create.blade.php template we need to create a base template that will be extended by the create template and all the other templates that will create later in this tutorial.

In the resources/views folder, create a base.blade.php file:

$ cd resources/views
$ touch base.blade.php

Open the resources/views/base.blade.php file and add the following blade template:

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 5.8 & MySQL CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
@yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>

Now, let's create the create.blade.php template. First, create a contacts folder in the views folder:

$ mkdir contacts

Next, create the template

$ cd contacts
$ touch create.blade.php

Open the resources/views/contacts/create.blade.php file and add the following code:

@extends('base')

@section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add a contact</h1>
<div>
@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('contacts.store') }}">
@csrf
<div class="form-group">
<label for="first_name">First Name:</label>
<input type="text" class="form-control" name="first_name"/>
</div>

      &lt;div class="form-group"&gt;
          &lt;label for="last_name"&gt;Last Name:&lt;/label&gt;
          &lt;input type="text" class="form-control" name="last_name"/&gt;
      &lt;/div&gt;

      &lt;div class="form-group"&gt;
          &lt;label for="email"&gt;Email:&lt;/label&gt;
          &lt;input type="text" class="form-control" name="email"/&gt;
      &lt;/div&gt;
      &lt;div class="form-group"&gt;
          &lt;label for="city"&gt;City:&lt;/label&gt;
          &lt;input type="text" class="form-control" name="city"/&gt;
      &lt;/div&gt;
      &lt;div class="form-group"&gt;
          &lt;label for="country"&gt;Country:&lt;/label&gt;
          &lt;input type="text" class="form-control" name="country"/&gt;
      &lt;/div&gt;
      &lt;div class="form-group"&gt;
          &lt;label for="job_title"&gt;Job Title:&lt;/label&gt;
          &lt;input type="text" class="form-control" name="job_title"/&gt;
      &lt;/div&gt;                         
      &lt;button type="submit" class="btn btn-primary-outline"&gt;Add contact&lt;/button&gt;
  &lt;/form&gt;

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

This is a screenshot of our create form!

Fill out the form and click on the Add contact button to create a contact in the database. You should be redirected to /contacts route which doesn't have a view associated to it yet.

R: Implementing the Read Operation and Getting Data

Next, let's implement the read operation to get and display contacts data from our MySQL database.

Go to the app/Http/Controllers/ContactController.php file, locate the index() method and update it:

    public function index()
{
$contacts = Contact::all();

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

Next, you need to create the the index template. Create a resources/views/contacts.index.blade.phpfile:

$ touch index.blade.php

Open the resources/views/contacts/index.blade.php file and add the following code:

@extends('base')

@section('main')
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Job Title</td>
<td>City</td>
<td>Country</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
@foreach($contacts as $contact)
<tr>
<td>{{$contact->id}}</td>
<td>{{$contact->first_name}} {{$contact->last_name}}</td>
<td>{{$contact->email}}</td>
<td>{{$contact->job_title}}</td>
<td>{{$contact->city}}</td>
<td>{{$contact->country}}</td>
<td>
<a href="{{ route('contacts.edit',$contact->id)}}" class="btn btn-primary">Edit</a>
</td>
<td>
<form action="{{ route('contacts.destroy', $contact->id)}}" method="post">
@csrf
@method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div>
</div>
@endsection

U: Implementing the Update Operation

Next, we need to implement the update operation. Go to the app/Http/Controllers/ContactController.php file, locate the edit($id) method and update it:

    public function edit($id)
{
$contact = Contact::find($id);
return view('contacts.edit', compact('contact'));
}

Next, you need to implement the update() method:

    public function update(Request $request, $id)
{
$request->validate([
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required'
]);

    $contact = Contact::find($id);
    $contact-&gt;first_name =  $request-&gt;get('first_name');
    $contact-&gt;last_name = $request-&gt;get('last_name');
    $contact-&gt;email = $request-&gt;get('email');
    $contact-&gt;job_title = $request-&gt;get('job_title');
    $contact-&gt;city = $request-&gt;get('city');
    $contact-&gt;country = $request-&gt;get('country');
    $contact-&gt;save();

    return redirect('/contacts')-&gt;with('success', 'Contact updated!');
}

Now, you need to add the edit template. Inside the resources/views/contacts/, create an edit.blade.php file:

$ touch edit.blade.php

Open the resources/views/contacts/edit.blade.php file and add this code:

@extends('base')
@section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Update a contact</h1>

    @if ($errors-&gt;any())
    &lt;div class="alert alert-danger"&gt;
        &lt;ul&gt;
            @foreach ($errors-&gt;all() as $error)
            &lt;li&gt;{{ $error }}&lt;/li&gt;
            @endforeach
        &lt;/ul&gt;
    &lt;/div&gt;
    &lt;br /&gt; 
    @endif
    &lt;form method="post" action="{{ route('contacts.update', $contact-&gt;id) }}"&gt;
        @method('PATCH') 
        @csrf
        &lt;div class="form-group"&gt;

            &lt;label for="first_name"&gt;First Name:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="first_name" value={{ $contact-&gt;first_name }} /&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;label for="last_name"&gt;Last Name:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="last_name" value={{ $contact-&gt;last_name }} /&gt;
        &lt;/div&gt;

        &lt;div class="form-group"&gt;
            &lt;label for="email"&gt;Email:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="email" value={{ $contact-&gt;email }} /&gt;
        &lt;/div&gt;
        &lt;div class="form-group"&gt;
            &lt;label for="city"&gt;City:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="city" value={{ $contact-&gt;city }} /&gt;
        &lt;/div&gt;
        &lt;div class="form-group"&gt;
            &lt;label for="country"&gt;Country:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="country" value={{ $contact-&gt;country }} /&gt;
        &lt;/div&gt;
        &lt;div class="form-group"&gt;
            &lt;label for="job_title"&gt;Job Title:&lt;/label&gt;
            &lt;input type="text" class="form-control" name="job_title" value={{ $contact-&gt;job_title }} /&gt;
        &lt;/div&gt;
        &lt;button type="submit" class="btn btn-primary"&gt;Update&lt;/button&gt;
    &lt;/form&gt;
&lt;/div&gt;

</div>
@endsection

U: Implementing the Delete Operation

Finally, we'll proceed to implement the delete operation. Go to the app/Http/Controllers/ContactController.php file, locate the destroy() method and update it accordingly:

    public function destroy($id)
{
$contact = Contact::find($id);
$contact->delete();

    return redirect('/contacts')-&gt;with('success', 'Contact deleted!');
}

You can notice that when we redirect to the /contacts route in our CRUD API methods, we also pass a success message but it doesn't appear in our index template. Let's change that!

Go to the resources/views/contacts/index.blade.php file and add the following code:

<div class="col-sm-12">

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

We also need to add a button to takes us to the create form. Add this code below the header:

    <div>
<a style="margin: 19px;" href="{{ route('contacts.create')}}" class="btn btn-primary">New contact</a>
</div>

This is a screenshot of the page after we created a contact:

Conclusion

We've reached the end of this tutorial. We created a CRUD application with Laravel 5.8, PHP 7.1 and MySQL.

Hope you enjoyed the tutorial and see you in the next one!


Originally published at techiediaries.com on 12 Mar 2019

=====================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ RESTful API with Laravel: Build a real API with Laravel

☞ Master Laravel - A php framework for Beginner to Advanced

☞ PHP with Laravel for beginners - Become a Master in Laravel

☞ Projects in Laravel: Learn Laravel Building 10 Projects

☞ Laravel 2019, the complete guide with real world projects

☞ Laravel for RESTful: Build Your RESTful API with Laravel

☞ Real Time Single Page Forum App with Pusher Laravel & vuejs

☞ Master Laravel PHP in 2019 for Beginners and Intermediate

PHP variable to JavaScript In Laravel

PHP variable to JavaScript In Laravel

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

However, we know the Laravel framework is having the largest community. Similarly, Laravel having large package base. So, sometimes it is easy to use package rather use custom code. Moreover, you can use existing packages.

Pass PHP variable to JavaScript

Many times you often find the need to pass PHP variable or string to the javascript file. But for this, you can use the below package.

Install package

Just copy below package and paste into the composer.json file.

"laracasts/utilities": "^2.1"

Or similarly from command line or terminal run command:

composer require laracasts/utilities

Provider

Further, add the Service provider into the config/app.php file. Which is used for the binding. After this, you will get Javascript facade.

'providers' => [
    '...',
    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
];

Publish the Configuration:

Finally, publish the config using the below command.

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Further, it will copy the javascript.js file to the config folder. There are two variable you can assign the values. Firstly, you can set bind_js_vars_to_this_view. This will set the name of the view. Basically, this is a partial view. If more than one view then you can set in array. Secondly, js_namespace is where you can define the namespace of the js variable. By default, Laracasts is the variable but you can change it to something else.

Usage in controller

Import the Dependency

You can initialize the JavaScript variable in the controller. Initialize and import into the controller.

use Javascript;

Set Variable

Now, you can define the variable into the controller using Javascript. You can set the values in the key-value pair. Assign a value to the key.

$array = [
    'key' => value_here,
];
 
JavaScript::put($array);

So, put your value into the JavaScript variable using the value of an array. Once you define into the array and assign to the variable you can access it into the js file.

Now, your controller will look like below.

<?php
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use JavaScript;
 
class VarController extends Controller
{
 
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        \JavaScript::put([
            'foo' => 'bar',
            'user' => 'user',
            'time' => '2019-04-29'
        ]);
        return view('pages/home');
    }
}

Access In JS file

Now, your blade file will look like below.

@extends('layouts.default')
@section('content')
    <div style="text-align:center">
        <h1>PHP var to JavaScript</h1>
         
    </div>
     
@stop
@section('scripts')
<script src='assets/app.js'></script>
@stop

In js file, you can access the set variable into the Laracasts namespace. Which you define in the javascript.js file.

console.log(Laracasts.foo); // access foo variable
console.log(Laracasts.user);// access user variable
console.log(Laracasts.time);// access time variable

In this way, you can directly access the set variable. This will give simple access for getting value into the js file. There is a limitation for getting the value into the js file. So this package will give you direct access into js file.

In many cases, this will give you the simplest solution. Many developers have to face this problem in developement. So, this post will give some relief from this problem. Let me know if you face any issue.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Integrate PHP Laravel 5.8 APIs in Angular 7

Integrate PHP Laravel 5.8 APIs in Angular 7

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API.

we commonly use PHP Laravel 5 for database integration and Angular for frontend single page applications. So it makes sense to write about integrating PHP Laravel APIs with Angular frontend.

1. Develop Laravel API

Lets setup the database first. We follow proper Laravel structure through commands and code.

1.1 Create Laravel API migration

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API. For User API to fetch and save data, you have to first setup database table. For that you have to write the migration for the table the command to create migration is written below.

php artisan make:migration create_user_table

After creating a migration, you have to make a model for the table that you have created. Which can be made by command written below.

1.2 Laravel model command

php artisan make:model User

short hand for creating migration and model both you will use this command

php artisan make:model User -m

After using this command the migration and model is made.

1.3 Laravel migration code example

Now you can write table in the migration. Below is the example to write table in migration.

public function up()
 {
 Schema::create('users', function (Blueprint $table) {
 $table-&gt;increments('id');
 $table-&gt;string('email')-&gt;unique();
 $table-&gt;string('first_name');
 $table-&gt;string('last_name');
 $table-&gt;string('password');
 $table-&gt;enum('account_status',['active','pending','rejected'])-&gt;default('pending');
 $table-&gt;enum('gender',['male','female']);
 $table-&gt;timestamps();
 });
 }

You can see the more about how to write table in the migration go to this link:

https://laravel.com/docs/5.7/migrations. After writing the table you have to run this command to migrate the table into the database

php artisan migrate

After migration, you have to write a method into the model that was created to get, update, or add data into the table. For an API to run you have to make,

Route::post('allUsers','[email protected]');

1. 4 Laravel controller command

php artisan make:controller UserController

1.4 Laravel controller code example

The controller function will look like this.

public function getAllUsers(){
 $count = User::All()-&gt;count();
 if($count &gt; 0){
 $users = User::role(['user','admin','dealer'])-&gt;get();
 return response()-&gt;json($users);
 }else{
 return response()-&gt;json("Users Not Found");
 }
 }

You can also make resource and collection to return the response. You can go this link and check the eloquent resources and collection https://laravel.com/docs/5.7/eloquent-resources.

So in this api the api is using UserController Method getllAllUsers to get the users from the database. After that you have to serve the laravel project to use these apis into angular project.

2. Integrate Laravel API in Angular

First setup your angular project using this command. Using Angular Cli.

ng new project_name

After that make your first component. For making component use this command.

ng generate component Users
// Or short hand:
ng g c Users

Four files will be generated after running that command. After that design your page in the html file

and in the ts file your code goes there. After that you have to make service to integrate the api calls that has been written in the Laravel so to create a service run this command.

ng generate service User
// Or short hand:
ng g s User

After running this command 2 file will be generated you will write the code in the ts file name users.service.ts there you will first import the HttpClient first. Then go to the environment folder and write the the api served url of the laravel project for local the url will look like this.

http://127.0.0.1:8000

The Laravel project will always serve on the 8000 port.

After importing the HttpClient then import the environment.ts file in the users service and get the api url from there. For importing just import the HttpClient into the constructor of the service.ts file.

After importing our service constructor will look like this.

 apiUrl: any;
constructor(private http: HttpClinet){
this.apiUrl = environment.apiUrl;
}

After that write a function to to call the API of the Laravel and we will use the HttpClient in the function an example is written below.

getAllUsers() {
 return this.http.get(this.apiUrl + 'allUsers/')
 .pipe(map((response: any) =&gt; {
 return response.json();
 }));
 }

This function is returning the data of all the users and parse then into the JSON response and return from where this function will get called.

After creating this function to get the data from the Laravel API now we will use this function into the the component that we have created first. To use the users service function import the users.service.ts file into the constructor of the users component. So this is the example to use the this service into the component.

The constructor will look like this after importing

constructor(private usersService: UsersService){
}

Here you can change the variable name for the user Service. You can set the variable name as you like. There is an ngOnInit() function in every component this is the first function to get called when ever the project gets served or this component is called. To get all the users from the service function that is calling Laravel API call to get all users the code will look like this.

allusers: any;
getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Here we have made first a global variable that is storing the response from the call into itself so that the response can be used the users.component.html file and anywhere in the users.component.ts file.

The getUsers function is calling the service function gellAllUsers to get the user and save it into the local variable. Now you can use this variable in whatever the way you like into your html page to show it on the webpage.

In Angular, you can also make the model to map the response also so for that you need to make a file names users.model.ts there is no specific command for that. So the model is made for the easiness to use the response of the API. Example is given below.

export class User{
 id: number;
 first_name: string;
 last_name: string;
 email: string;
 gender: string;
 status: string;
}

For mapping the response on to the model we will use Observables. Observable provide the support for passing the messages between creators of the observables and the subscribers in our application. Here the subscriber will be our getUsers function in the users.component.ts file and the Observable will be defined in the users.service.ts.

For using observers we will import the rxjs Observable into the users.service.ts file. Then after that the Observable will be used like this as shown in example below.

getUsers(): Observable&lt;{data: Users[]}&gt;{
 const headers = new HttpHeaders({'Content-Type': 'application/json'});
 return this.http.get&lt;{status_code: number, data: Users[], message: string}&gt;(this.apiUrl +
'allUsers', {headers: headers});
 }

Here the observable is parsing the response into the user model which we have created above as we are getting all the users from the API response so we are use Users[] array. And to get its parsed over here you have to format the response also in the Laravel API function. After this we also need to change the users.component.ts file so it will look like this.

 

allusers: Users[];

First we need to make your allUsers variable type to Users[] as the model and as we have done it in the service file the the gellUsers function will able to map response now.

getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Now it has made it easy for you to get the variable easily that are in the users model if you want to see the firstname of all the users you can easily do this

this.allusers.foreach(element =&gt;{
console.log('First Name',element.firstname);
})

as firstname is the variable that is in the model of Users.

If you follow this detailed tutorial, you can learn to write the APIs in Laravel and to integrate them in Angular project.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

This post was originally published here