How to Create a Laravel 6.8 CRUD Web Application from Scratch

How to Create a Laravel 6.8 CRUD Web Application from Scratch

This Laravel 6.8 CRUD tutorial explains how to create a Laravel 6.8 CRUD (Create, Read, Update, Delete) web application step by step from scratch. We will build a PHP based web application and also learn how to store data in MySQL database with Laravel 6.8 PHP framework. How to create Laravel 6.8 CRUD App with PHP 7.3 and MySQL Database. Laravel 6.8 CRUD operations and form validation tutorial with examples.

Today we will be learning how to create a Laravel 6.8 CRUD (Create, Read, Update, Delete) web application step by step from scratch. We will build a PHP based web application and also learn how to store data in MySQL database with Laravel 6.8 PHP framework.

We will create a student management CRUD app using PHP 7.3 and MySQL. In this app, a user can create, read, update, and delete the student’s data from the MySQL database using the Laravel framework.

Laravel Advantages

Laravel is a PHP based web application framework with an eloquent, refined syntax. Developing an app with Laravel has loads of advantages; some of them are mentioned below.

  • Great Security
  • MVC Architecture
  • Database Migration
  • Simple Unit Testing
  • Improved Performance
  • Multi-lingual Support
  • Robust Authentication
  • Developer-friendly Code
  • Blade Templating Support
  • Object-Oriented Libraries
  • Open Source & Strong Community

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern and based on Symfony. Some of the features of Laravel are a modular packaging system with a dedicated dependency manager, different ways for accessing relational databases, utilities that aid in application deployment and maintenance, and its orientation toward syntactic sugar.
wikipedia

Table of Contents

  • Server Specification
  • Installing PHP Composer Package
  • Creating a Laravel 6.8 Project
  • Set Up MySQL Database in Laravel
  • Setting Up Migration and Model
  • Adding Controller and Creating Routes
  • Create Views in Laravel with Blade Templates
  • Create, Store & Validate User Data in MySQL Database
  • Show Users Data
  • Edit and Update Data
  • Conclusion
Server Specification

The following are the server specifications to run the Laravel smoothly.

  • PHP >= 7.2.0
  • XML PHP Extension
  • PDO PHP Extension
  • JSON PHP Extension
  • Ctype PHP Extension
  • BCMath PHP Extension
  • OpenSSL PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
Installing PHP Composer Package

Composer is a dependency manager for PHP libraries.

Head over to home directory:

cd ~

Next, run the following command to install the Composer using curl:

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

Run the following command to install composer globally on your machine:

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

By running the following command, you can identify the Composer version installed on your machine. However, we have installed Composer 1.9.

composer

This will be displayed on your terminal:

    ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.9.1 2019-11-01 17:20:17

Usage:
  command [options] [arguments]

Once the Composer is installed in your system, then you are ready to build a Laravel 6.8 CRUD project.

Creating a Laravel 6.8 Project

Go to your terminal and run the following command to build a Laravel 6 project.

composer create-project laravel/laravel --prefer-dist laravel-6-crud-app

Get inside the PHP Laravel project folder.

cd laravel-6-crud-app

Run the below command to verify the installed Laravel version.

php artisan -V

# Laravel Framework 6.8.0
Set Up MySQL Database in Laravel

In this step, we will make the MySQL database connection in our PHP Laravel app. Following database variables need to be updated database name, username, password.
We must set up MySQL db before we get started with migrations. I assume you already know how to configure the database with PHPMyAdmin., Create the MySQL database, I have named it laravel6crud.

Once we are done creating a database, then we will insert MySQL db details in our .env file inside our Laravel 6.8 CRUD app.

Laravel project contains the .env file, as the name suggests, It is a local where you keep all your database configurations, such as database credentials, mail driver details, cache drivers, etc.

However, it is not considered a good practice to store such credentials within the code directly. The .env files are not just limited to php; preferably, It is also utilized in different frameworks as well.

Now, a few essential points to be noted. If you make any changes in the .env configuration files, then you should restart the server.

In case you are using a virtual host, then you should run the following command via your terminal to clean the configuration cache.

php artisan config:clear

Open the .env file and place the following code in it:

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

If you are using MAMP on a macOS add the following line at the end of your .env configuration file.

DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
Setting Up Migration and Model

We have created the database and configured the database by adding the credentials in the env file. Now, we will learn how to set the migration by adding the data properties in the MySQL table.

We need to create a Model and Migration file to create the migrations, run the following command.

php artisan make:model Student -m

Inside your Laravel project, you can check out migration files in the database/migrations folder. By default Laravel generates THE following files:

  • timestamp__create_users_table.php
  • timestamp_create_password_resets_table.php
  • timestamp_create_failed_jobs_table.php

Next, we will add the schema inside our migration file, open the migration file go to database > migrations > timestamp_create_students_table.php file, and add the following schema inside of it.

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->string('phone');
            $table->string('password');
            $table->timestamps();
        });
    }

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

As you can see there are two types of functions inside the migration files:

The up() function allows creating/updating tables, columns, and indexes.

The down() function allows reversing an operation done by up method.

Next, we will add the $fillable property in the Student model, go to app > Student.php file and add the given below code.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends model
{
    protected $fillable = ['name', 'email', 'phone', 'password'];
}

Fillable property is used inside the model, and it determines which data types or fields are mass-assignable in the database table.

Next, we have to run the following command to create the table in the database:

php artisan migrate

# Migration table created successfully.
# Migrating: 2014_10_12_000000_create_users_table
# Migrated:  2014_10_12_000000_create_users_table (0.24 seconds)
# Migrating: 2014_10_12_100000_create_password_resets_table
# Migrated:  2014_10_12_100000_create_password_resets_table (0.23 seconds)
# Migrating: 2019_08_19_000000_create_failed_jobs_table
# Migrated:  2019_08_19_000000_create_failed_jobs_table (0.12 seconds)
# Migrating: 2019_12_19_174332_create_students_table
# Migrated:  2019_12_19_174332_create_students_table (0.14 seconds)
Adding Controller and Creating Routes

Next, we are going to generate StudentController, run the below command to create a new controller for our PHP 7.3 CRUD app.

php artisan make:controller StudentController --resource

The above command generated a brand new file with this path app/Http/Controllers/StudentController.php. By default, there are seven methods defined in it, which are as follows:

  • index() => shows student list
  • create() => creates a student using a form
  • store() => creates a student in the database
  • show() => shows a specific student
  • edit() => updates the student data using a form
  • update() => updates the student data using a form
  • destroy() => removes a particular student

Now, we will start writing the code in StudentController.php file to initialize the CRUD operations for our PHP app.

<?php

namespace App\Http\Controllers;

use App\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $student = Student::all();
        return view('index', compact('student'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $storeData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        $student = Student::create($storeData);

        return redirect('/students')->with('completed', 'Student has been saved!');
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $student = Student::findOrFail($id);
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $updateData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        Student::whereId($id)->update($updateData);
        return redirect('/students')->with('completed', 'Student has been updated');
    }

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

        return redirect('/students')->with('completed', 'Student has been deleted');
    }
}

Configure Routes

Head over to routes > web.php file, here we will add the StudentController at the end of this file.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */

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

Route::resource('students', 'StudentController');

Run the following command to create the various routes for our CRUD app.

php artisan route:list

Create Views in Laravel with Blade Templates

Now, we have to build the views for our student CRUD app with blade files. Go to resources/views folder and create the following blade templates in our Laravel project.

  • layout.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php

Configure Bootstrap in Laravel 6.8 project

Add the following code in the layout.blade.php template. Here, we defined the main layout for our app along with that we implemented Bootstrap UI framework via Stackpath CDN.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Laravel 6.8 CRUD App Example</title>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
   </head>
   <body>
      <div class="container">
         @yield('content')
      </div>

      <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" type="text/js"></script>
   </body>
</html>

In the next step, we will also configure the following views template.

Create, Store & Validate User Data in MySQL Database

We have to create a form to create, store and validate a user data using Bootstrap Form and Card UI components.

Add the following code in the resources/views/create.blade.php file.

@extends('layout')

@section('content')

<style>
    .container {
      max-width: 450px;
    }
    .push-top {
      margin-top: 50px;
    }
</style>

<div class="card push-top">
  <div class="card-header">
    Add User
  </div>

  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('students.store') }}">
          <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="email">Email</label>
              <input type="email" class="form-control" name="email"/>
          </div>
          <div class="form-group">
              <label for="phone">Phone</label>
              <input type="tel" class="form-control" name="phone"/>
          </div>
          <div class="form-group">
              <label for="password">Password</label>
              <input type="text" class="form-control" name="password"/>
          </div>
          <button type="submit" class="btn btn-block btn-danger">Create User</button>
      </form>
  </div>
</div>
@endsection

To generate a new user, we are using cerate() mehtod, which is specified in the ShowController.php file.

// StudentController.php

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $storeData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        $student = Student::create($storeData);

        return redirect('/students')->with('completed', 'Student has been saved!');
    }

Once you click on the submit button, user data is written inside the students table in MySQL db.

Show Users Data

Now, we have to display the users’ data using the Bootstrap table. The index() function returns an index view with data retrieved from the mysql database. Add the given below code inside the index function.

// StudentController.php

 public function index()
    {
        $student = Student::all();
        return view('index', compact('student'));
    }

Add the following code in the resources/views/index.blade.php file.

@extends('layout')

@section('content')

<style>
  .push-top {
    margin-top: 50px;
  }
</style>

<div class="push-top">
  @if(session()->get('success'))
    <div class="alert alert-success">
      {{ session()->get('success') }}  
    </div><br />
  @endif
  <table class="table">
    <thead>
        <tr class="table-warning">
          <td>ID</td>
          <td>Name</td>
          <td>Email</td>
          <td>Phone</td>
          <td>Password</td>
          <td class="text-center">Action</td>
        </tr>
    </thead>
    <tbody>
        @foreach($student as $students)
        <tr>
            <td>{{$students->id}}</td>
            <td>{{$students->name}}</td>
            <td>{{$students->email}}</td>
            <td>{{$students->phone}}</td>
            <td>{{$students->password}}</td>
            <td class="text-center">
                <a href="{{ route('students.edit', $students->id)}}" class="btn btn-primary btn-sm"">Edit</a>
                <form action="{{ route('students.destroy', $students->id)}}" method="post" style="display: inline-block">
                    @csrf
                    @method('DELETE')
                    <button class="btn btn-danger btn-sm"" type="submit">Delete</button>
                  </form>
            </td>
        </tr>
        @endforeach
    </tbody>
  </table>
<div>
@endsection

Check this template on the following URL: http://127.0.0.1:8000/students/create

To show the user data in the tabular format, we are going to loop over the students’ array, and don’t forget to add edit and delete button to modify the Laravel app.

Edit and Update Data

To edit and update the user information, we are using the below functions in StudentController.php file.

// StudentController.php

     /**
     * Edit the specified resource.
     */
    public function edit($id)
    {
        $student = Student::findOrFail($id);
        return view('edit', compact('student'));
    }

    /**
     * Update the specified resource in db.
     */
    public function update(Request $request, $id)
    {
        $updateData = $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|max:255',
            'phone' => 'required|numeric',
            'password' => 'required|max:255',
        ]);
        Student::whereId($id)->update($updateData);
        return redirect('/students')->with('completed', 'Student has been updated');
    }

To edit and update data in MySQL database we are going to add the following code inside the resources/views/edit.blade.php file.

@extends('layout')

@section('content')

<style>
    .container {
      max-width: 450px;
    }
    .push-top {
      margin-top: 50px;
    }
</style>

<div class="card push-top">
  <div class="card-header">
    Edit & Update
  </div>

  <div class="card-body">
    @if ($errors->any())
      <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
            @endforeach
        </ul>
      </div><br />
    @endif
      <form method="post" action="{{ route('students.update', $student->id) }}">
          <div class="form-group">
              @csrf
              @method('PATCH')
              <label for="name">Name</label>
              <input type="text" class="form-control" name="name" value="{{ $student->name }}"/>
          </div>
          <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="email" value="{{ $student->email }}"/>
          </div>
          <div class="form-group">
              <label for="phone">Phone</label>
              <input type="tel" class="form-control" name="phone" value="{{ $student->phone }}"/>
          </div>
          <div class="form-group">
              <label for="password">Password</label>
              <input type="text" class="form-control" name="password" value="{{ $student->password }}"/>
          </div>
          <button type="submit" class="btn btn-block btn-danger">Update User</button>
      </form>
  </div>
</div>
@endsection

Start the app in the browser by running the given below command:

php artisan serve

Check out the Laravel App Routes:

Create Student: http://127.0.0.1:8000/students/create

Students List: http://127.0.0.1:8000/students

Conclusion

We have finished Laravel 6.8 CRUD operations and form validation tutorial with examples. To compare the code, you should check out my Github repository.

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 / MySQL - Count how many table in database contain Specific name

I'm building an admin to control an interactive game, and I'm using PHP/MySql to store all the data for all the rounds. Each of the tables that I want to load into the game via PHP are titled "Puzzle*" with the * being an incremental index number. There are a few other tables in my database for global game data and bonus rounds.

I'm building an admin to control an interactive game, and I'm using PHP/MySql to store all the data for all the rounds. Each of the tables that I want to load into the game via PHP are titled "Puzzle*" with the * being an incremental index number. There are a few other tables in my database for global game data and bonus rounds.

What I want to be able to do is count the number of tables in my database that contain the name "Puzzle", and then use that total number as a randomizer to select a puzzle randomly. I plan to have roughly 50 puzzles, so an automated way of selecting a random puzzle, and then if I want to select another puzzle - to remove that previous puzzle from the list so that there is no chance of it being repeated until I start the whole game over again.

MySQL Database

Database Name: puzzleGame
Table 1: puzzle1
Table 2: puzzle2
Table 3: puzzle3
Table 4: puzzle4
Table 5: globals
Table 6: bonus


Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

Clear Cache in Laravel 6.8 App using Artisan Command Interface (CLI)

In Laravel 6 tutorial, we learn how to use PHP artisan command interface (CLI) to clear the cache from Laravel 6.8 application. How To Clear Cache in Laravel 6.8 Application using Artisan Command Line Interface (CLI)? How to clear route cache using php artisan command? How to easily clear cache in Laravel application? How to clear config cache in PHP Laravel via artisan command? How to clear Laravel view cache? How to Reoptimized class in Laravel via artisan CLI?

Today in this tutorial, we are going to learn how to clear route cache, laravel application cache, config cache, view cache and reoptimized class in a Laravel 6.8 application using artisan command-line interface.

I’m pretty sure many of you may have found yourself gotten into the situation where you do not see changes in the view after making the changes in the app.

Laravel application serves the cached data so caching problem occurs due to the robust cache mechanism of Laravel.

But, if you are still facing this issue, then you do not have to worry further. Let me do the honour of introducing you some of the best artisan commands to remove the cache from your Laravel app via PHP artisan command line interface.

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application.

Table of Contents

  • Clear Route Cache in Laravel
  • Clear Laravel Application Cache
  • Clear Config Cache via PHP Artisan
  • Clear Laravel View Cache
  • Reoptimized Class
Clear Route Cache in Laravel

Laravel caching system also takes routes in consideration, to remove route cache in Laravel use the given below command:

php artisan route:cache
Clear Application Cache in Laravel

Run the following command to clear application cache:

php artisan cache:clear
Clear Config Cache in Laravel

Run the following command to clear config cache:

php artisan config:cache
Clear View Cache in Laravel

Run the following command to clean your view cache:

php artisan view:clear
Reoptimize Class

Run the below command to reoptimize the class loader:

php artisan optimize

Conclusion

We have completed this Laravel 6 tutorial, In this tutorial we learned how to use php artisan command to clear the cache from your Laravel application. We have answered the following questions in this article.

  • How to clear route cache using php artisan command?
  • How to easily clear cache in Laravel application?
  • How to clear config cache in PHP Laravel via artisan command?
  • How to clear Laravel view cache?
  • How to Reoptimized class in Laravel via artisan CLI?

Now, it’s your time to let me know what do you think about this laravel 6 article. Go forth and try these super awesome artisan commands and let me know how these commands are helping you.