Showing posts with label laravel eloquent migration. Show all posts
Showing posts with label laravel eloquent migration. Show all posts

Laravel Eloquent ORM Query and Model Feature

Laravel Eloquent ORM Query from Scratch

Laravel Eloquent feature is object Oriented paradigm approach of database communication. In Eloquent we create Model for each Table in the database, which set the communication (Fetching, Inserting, Deleting, Modifying the Record ) with database.

You can create the Model with Migration or without migration with the help of Artisan Command. We can use -m or --migration after the artisan command to create the Model with Migration. Below code  is the Example.

Eloquent Model with Database Migration


Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

                  php artisan make:model model-Name  --migration (--migration is for migration )

This above two Artisan Command will create Table migration file in your databaese / migration directory which you can modify further.

Create Model without Migration. Below is the Artisan command to create Model.

  php artisan make:model model-Name 

Lets Take Example, We will create Model Named with CategoryMaster 


php artisan make:model CategoryMaster  -m


This above Artisan Command will create the Model named with CategoryMaster.  Below is the code for your reference   

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CategoryMaster extends Model
{     // }

Eloquent Model Property


In the above model, we didn't mention the table. So we have to declare the table in CategoryMaster Model.

protected  $table = '"category_table";

In Eloquent Model, Eloquent consider by default each table has a primary key id with incrementing integer Value. How to Define a protected Primary key property:

protected  $primaryKey = '"id";

protected  $incrementing = '"false";

if Primary Key is not an integer then you must set the KeyType a string.

protected $keyType = 'string';

Once the Table is declared in the Model, By Default timestamp (Created_at, updated_at) will be true. If you don't want them then you have to set the timestamp to false.

protected $timeStamp = "false";

Eloquent Model and Database Connection


Eloquent model will use Default Database which got configured with your laravel Application. if you wish to have your model connected with other database then you have to use $connection Property. Code is below for your reference.

protected $connection = "Connection-Database-Name"; 

Fetch / Retrieve Model In Eloquent

Once the Model is Created with Associated table, We can perform all the database operation(CRUD) on it. We will Query / fetch database table associated with model step by step.

Above we have created CategoryMaster  Model, Now we will use this model for writing our Eloquent Query as a Example.

$data= App\CategoryMaster::all();

all() method in Eloquent will return all result from the specified model table. We can use various constraint on the all method to filter the table record.

$data = App\CategoryMaster::where('status', 1)->orderBy('id', 'desc')
        ->take(5)->get();

As Eloquent is Query Builder you can use all the Query Builder method for database Operation.


Laravel Model and Database Migration From Scratch

Laravel Database Migration


Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


create migration in laravel

Step 1: Create Laravel Project with Name anyQuestion using Composer. Command to create project in laravel is below.

composer create-project --prefer-dist laravel/laravel anyQuestion "6.*"

anyQuestion is our Laravel Project name. Below is the Screen what will appear while creating the project using Command prompt.


Step 2: Create Database named with anyQuestion_db in Xampp or whatever server tool you use. Open .env file in your laravel project and configure your Database with password and all.

Step 3:  Use Php Artisan Command to create model and controller in your project.

php artisan make:controller controllerName

This above artisan command will create normal controller without default function.

php artisan make:controller controllerName --resource

This above Artisan Command will create controller with default function in it. All the default Function list is below.

  • public function index(){ }
  • public function create(){ }
  • public function store(Request $request){ }
  • public function show($id) { }
  • public function edit($id) { }
  • public function update(Request $request, $id){ }
  • public function destroy($id) { }

If we are creating the Controller with --resource then by default all the above function will be created and creating route for all the above function will be time consuming process. So view the route list first using below artisan command. below command will give you all the route list.

php artisan route:list

How to define single route which will point all the above function based on the requirement.

 Route::resource('route-name','controller-Name');

Again hit the php artisan route:list  And you can view all the route list for default controller function.

Now create Model using artisan command, below is the command

php artisan make:model model-Name

Above command will create the simple model with sample model name what is provided with the command.

Laravel Run Migrations


Database migration concept start with model here. Database migration in Laravel provide the facility to create, manage and modify the database. Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

Now check your Migration folder inside Database Folder in the anyQuestion project root.

In the migration folder the migration file will be created and if you open that you will get default up() function and down() function.

   public function up()
     {
        Schema::create('post_masters', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
     }

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

If you check the post_master migration file, In up() function we are creating post_masters table.  By default there is 'id' column and the timestamp which will give us the 'created_at', 'updated_at' column.

Once you have created the model with migration you don't have to touch the Database to create table. You can directly migrate the file using below command which will create the table in the database. To add column or remove column you just make change in the migration file. and using artisan command it will reflect in the Database. Command to migrate the files.

Before Migration go to Provide Folder and Open the AppServiceProvider.php file and add this line of code. Open AppServiceProvider.php file

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 
}

Once change is made run the migration Command which is below for your reference.

php artisan migrate

The Artisan command will run it will create the table automatically in the Database..

How to insert the record in Database using Artisan Command


Insert Data Using Tinker

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on Aโ€™s House, the t...

Our Popular Post