Email: info@zenconix.com

Steps by step procedure to connect the database to Lumen



Visit Site:

Overview

  1. Create database in phpmyadmin
  2. Open .env file. NOTE: if .env file is with name, .env.sample, then rename it to .env
  3. Change following parameter in file
    1. DB_DATABASE=lumen
    2. DB_USERNAME=root
    3. DB_PASSWORD=
  4. Also check for following parameters if they are different than default setting
    1. DB_HOST=127.0.0.1
    2. DB_PORT=3306
  5. Next, as we are going to use Eloquent ORM, we need to un-comment some lines from bootstrap/app.php
    1. $app→withEloquent()
    2. $app→withFacades();
  6. open command prompt, go to project location and run following command
    php artisan make:migration create_users_table
  7. It will create new file for migration in Database/migration folder, by name “DateTime_create_user_table.php
  8. If we need to add custom columns, then add as below.
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');

            //create custom fields, we are going to add username, email and api_token
            $table->string('username');
            $table->string ('email');
            $table->text('api_token');
            $table->timestamps();
        });
    }
  1. Then run command php artisan migrate to migrate this table to database.

Reference and detailed documentation

Features

Specifications

Preview

Laravel – How to create Seed users



Visit Site:

Overview

Create migration file to create new users table

To create migration, open command prompt and execute following command

php artisan make:migration create_users_table

This will create new file in database/migration folder by name datatime_create_users_table.php

Open file and modify as below.

<?php

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

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

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

Define Model Factories

Now open ModelFactory.php from database/factories folder and define our model as below.

<?php
use Illuminate\Support\Facades\Hash;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email'    => $faker->unique()->email,
        'password'=>Hash::make('12345')
    ];
});

Create User Table Seeder

Create new file UsersTableSeeder.php and create UsersTableSeeder class in database\seeds\UsersTableSeeder.php and add code snipate as below

<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // create 10 users using the user factory
        factory(App\User::class, 10)->create();
    }
}

With this function, it will create 10 dummy users in users table.

Register User Seeder

We need to register newly created seeder in DatabaseSeeder.

Open database/seeds/DatabaseSeeder.php file and add below code.

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
          Model::unguard();
        // Register the user seeder
        $this->call(UsersTableSeeder::class);
        Model::reguard();
    }
}

Changes in AppServiceProvider

If you try to run migration commands you will face error as below.

    [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter tabl e users add unique users_email_unique(email))

    [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

To resolve this type of error, open app\providers\AppServiceProvider.php file and add below code

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Schema\Builder;
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
    function boot()
    {
        Builder::defaultStringLength(191); // Update defaultStringLength
    }
}

Run commands to migrate and create dummy data

Now, open command prompt and add below commands
To create table in database, execute following command

php artisan migrate

To create seed users, execute following command

php artisan db:seed

Features

Specifications

Preview

Laravel – Create Common Response builder for all responses



Visit Site:

Overview

Create Helper function

Create new folder in app/http/ by name Helpers

Create new file ResponseBuilder.php

Create new class in ReponseBuilder.php with function with same name as file, so class name will be ResponseBuilder

first we need to add namespace, as our file is in app\http\Helpers folder, namespace for the file would be namespace App\Http\Helpers;

<?php
    namespace App\Http\Helpers;

    class ResponseBuilder
    {
        public static function Result($status="", $information="", $data="")
        {
            return [
                "success"=>$status,
                "information"=>$information,
                "data"=>$data
            ];
        }
    }
?>

Note: here we have created static function, so later we can directly use it without initialization of object using :: operator.

Call Helper function in GET method

public function GetAllPost()
{
        //return Post::all();
        $data = Post::all();
        $status = true;
        $information= "Data is fetched successfully";

        return ResponseBuilder::Result($status, $information, $data)
}

Call Helper function in POST Method

public function AddPost(Request $request)
    {
        $post = new Post;

        $post->id = $request->input('id');
        $post->title = $request->input('title');
        $post->content = $request ->input('content');
        //$post->save();
        $result = $post->save();
        if($result == 1)
        {
            $status = true;
            $information = "Data added successfully";
        }
        else
        {
            $status = false;
            $information ="Data not added successfully";
        }
        return ResponseBuilder::Result($status, $information);
    }

Create Routes

//add post
$router->post('/addpost', 'PostController@AddPost');
//get all posts
$router->get('/getallpost','PostController@GetAllPost');

Features

Specifications

Preview