How to create Model?

models are stored by default in the root of the app directory. The User model bydefault created by the Laravel framework.

if you want to create other more models, you can simply run the artisan command below.

php artisan make:model model_Name(User)

where model_Name represents the name of the model you want to create

############## Or ##################

php artisan make:model Student -m

This command will create a Student model and also create migration table. -m for migration.

Open Model User Class (app/User.php)

Here Add Some column in $fillable array. which column you want to add your table.

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
use Notifiable;

/**
* The attributes that are mass assignable.
*
* @var array
*/

public $timestamps = FALSE;


protected $fillable = [
'name','email', 'password','mobile',
];

/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
/*
protected $hidden = [
'password', 'remember_token',
];
*/
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}


How to create database table

To create a migration, use the make:migration Artisan command

php artisan make:migration create_users_table

Created Migration: 2020_04_14_165730_create_users_table

The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations.


create table

The --table and --create options may also be used to indicate the name of the table and whether or not the migration will be creating a new table.

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users


Migration Structure

php artisan make:migration create_users_table

A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.

<?php

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

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

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

Add Some Column in your table.

<?php

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

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')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->increments('id');
$table->integer('answers')->default(0);
$table->integer('points')->default(0);
$table->text('name');
$table->text('color');
$table->text('text')->nullable();
$table->boolean('status')->default(true);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id') ->on('users') ->onDelete('restrict');
$table->timestamps();
});
}

/**

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name',32);
$table->string('email',64)->unique();
$table->string('password',128);


//$table->rememberToken();
$table->string('remember_token',164)->nullable();
$table->timestamps();
//$table->timestamp('email_verified_at')->nullable();
});
}
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

Running Migrations

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

Migration table created successfully.
Migrating: 2020_04_17_074320_create_users_table
Migrated: 2020_04_17_074320_create_users_table (0.35 seconds)

The above command create users table and also create given column in your table in database


Forcing Migrations To Run In Production

Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the --force flag:

php artisan migrate --force

Rolling Back Migrations

To roll back the latest migration operation, you may use the rollback command. This command rolls back the last "batch" of migrations, which may include multiple migration files:

php artisan migrate:rollback

You may roll back a limited number of migrations by providing the step option to the rollback command. For example, the following command will roll back the last five migrations:


php artisan migrate:rollback --step=5


migrate:reset

The migrate:reset command will roll back all of your application's migrations:
php artisan migrate:reset

Roll Back & Migrate Using A Single Command

The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database

php artisan migrate:refresh

// Refresh the database and run all database seeds...
php artisan migrate:refresh --seed

Drop All Tables & Migrate

The migrate:fresh command will drop all tables from the database and then execute the migrate command

php artisan migrate:fresh
php artisan migrate:fresh --seed

Creating & Dropping Tables

To create a new database table, use the create method on the Schema facade. The create method accepts two arguments: the first is the name of the table, while the second is a Closure which receives a Blueprint object that may be used to define the new table:

Schema::create('users', function (Blueprint $table) {
$table->id();
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});


Schema::create('users', function($table)
{
$table->increments('id');
});

The first argument passed to the create method is the name of the table, and the second is a Closure which will receive a Blueprint object which may be used to define the new table.


Checking For Table / Column Existence

You may check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}

Database Connection & Table Options

If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:

Schema::connection('itechxpert')->create('users', function (Blueprint $table) {
$table->id();
});


Renaming / Dropping Tables

To rename an existing database table, use the rename method:

Schema::rename($from, $to);

To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop('users');
Schema::dropIfExists('users');

Creating Columns (Adding Column in table)

The table method on the Schema facade may be used to update existing tables.

the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance you may use to add columns to the table:

Schema::table('users', function (Blueprint $table) {
$table->string('email');
});

How to create foregin key with relation.

public function up()
{
Schema::create('meals', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('user_id'); //changed this line
$table->unsignedBigInteger('category_id'); //changed this line
$table->string('title');
$table->string('body');
$table->string('meal_av');
$table->timestamps();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');

$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
}

SQLSTATE[HY000]: General error: 1005 Ca
n't create table `grocery`.`#sql-4bb0_c1` (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table `subcategories` add constraint `subcateg
ories_category_id_foreign` foreign key (`category_id`) references `categories` (
`id`) on delete cascade)

Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('owner_id');
$table->string('title');
$table->text('description');
$table->timestamps();

$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});



its show foreign key error


Solution :-

Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('owner_id')->index();
$table->string('title');
$table->text('description');
$table->timestamps();
$table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
});

perfectly run.


In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
You create the id fields in both users and firms as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail. You need to either add the unsigned clause to the id field definitions, or remove the unsigned clause from the foreign key fields.

just add ->unsigned()->index() at the end of the foreign key and it will work.

public function up()
{
Schema::create('meals', function (Blueprint $table) {
$table->increments('id');
$table->unsignedBigInteger('user_id'); //changed this line
$table->unsignedBigInteger('category_id'); //changed this line
$table->string('title');
$table->string('body');
$table->string('meal_av');
$table->timestamps();

$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');

$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
});
}


Available Column Types

$table->id(); Alias of $table->bigIncrements('id').
$table->foreignId('user_id'); Alias of $table->unsignedBigInteger('user_id').
$table->bigIncrements('id'); Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes'); BIGINT equivalent column.
$table->binary('data'); BLOB equivalent column.
$table->boolean('confirmed'); BOOLEAN equivalent column.
$table->char('name', 100); CHAR equivalent column with a length.
$table->date('created_at'); DATE equivalent column.
$table->dateTime('created_at', 0); DATETIME equivalent column with precision (total digits).
$table->dateTimeTz('created_at', 0); DATETIME (with timezone) equivalent column with precision (total digits).
$table->decimal('amount', 8, 2); DECIMAL equivalent column with precision (total digits) and scale (decimal digits).
$table->double('amount', 8, 2); DOUBLE equivalent column with precision (total digits) and scale (decimal digits).
$table->enum('level', ['easy', 'hard']); ENUM equivalent column.
$table->float('amount', 8, 2); FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions'); GEOMETRY equivalent column.
$table->geometryCollection('positions'); GEOMETRYCOLLECTION equivalent column.
$table->increments('id'); Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer('votes'); INTEGER equivalent column.
$table->ipAddress('visitor'); IP address equivalent column.
$table->json('options'); JSON equivalent column.
$table->jsonb('options'); JSONB equivalent column.
$table->lineString('positions'); LINESTRING equivalent column.
$table->longText('description'); LONGTEXT equivalent column.
$table->macAddress('device'); MAC address equivalent column.
$table->mediumIncrements('id'); Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger('votes'); MEDIUMINT equivalent column.
$table->mediumText('description'); MEDIUMTEXT equivalent column.
$table->morphs('taggable'); Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->uuidMorphs('taggable'); Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns.
$table->multiLineString('positions'); MULTILINESTRING equivalent column.
$table->multiPoint('positions'); MULTIPOINT equivalent column.
$table->multiPolygon('positions'); MULTIPOLYGON equivalent column.
$table->nullableMorphs('taggable'); Adds nullable versions of morphs() columns.
$table->nullableUuidMorphs('taggable'); Adds nullable versions of uuidMorphs() columns.
$table->nullableTimestamps(0); Alias of timestamps() method.
$table->point('position'); POINT equivalent column.
$table->polygon('positions'); POLYGON equivalent column.
$table->rememberToken(); Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->set('flavors', ['strawberry', 'vanilla']); SET equivalent column.
$table->smallIncrements('id'); Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger('votes'); SMALLINT equivalent column.
$table->softDeletes('deleted_at', 0); Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes with precision (total digits).
$table->softDeletesTz('deleted_at', 0); Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes with precision (total digits).
$table->string('name', 100); VARCHAR equivalent column with a length.
$table->text('description'); TEXT equivalent column.
$table->time('sunrise', 0); TIME equivalent column with precision (total digits).
$table->timeTz('sunrise', 0); TIME (with timezone) equivalent column with precision (total digits).
$table->timestamp('added_on', 0); TIMESTAMP equivalent column with precision (total digits).
$table->timestampTz('added_on', 0); TIMESTAMP (with timezone) equivalent column with precision (total digits).
$table->timestamps(0); Adds nullable created_at and updated_at TIMESTAMP equivalent columns with precision (total digits).
$table->timestampsTz(0); Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns with precision (total digits).
$table->tinyIncrements('id'); Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes'); TINYINT equivalent column.
$table->unsignedBigInteger('votes'); UNSIGNED BIGINT equivalent column.
$table->unsignedDecimal('amount', 8, 2); UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger('votes'); UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes'); UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes'); UNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger('votes'); UNSIGNED TINYINT equivalent column.
$table->uuid('id'); UUID equivalent column.
$table->year('birth_year'); YEAR equivalent column.

Column Modifiers

there are several column "modifiers" you may use while adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

Schema::table('users', function (Blueprint $table) {
$table->string('email')->nullable();
});


Modifier Description
->after('column') Place the column "after" another column (MySQL)
->autoIncrement() Set INTEGER columns as auto-increment (primary key)
->charset('utf8') Specify a character set for the column (MySQL)
->collation('utf8_unicode_ci') Specify a collation for the column (MySQL/PostgreSQL/SQL Server)
->comment('my comment') Add a comment to a column (MySQL/PostgreSQL)
->default($value) Specify a "default" value for the column
->first() Place the column "first" in the table (MySQL)
->nullable($value = true) Allows (by default) NULL values to be inserted into the column
->storedAs($expression) Create a stored generated column (MySQL)
->unsigned() Set INTEGER columns as UNSIGNED (MySQL)
->useCurrent() Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
->virtualAs($expression) Create a virtual generated column (MySQL)
->generatedAs($expression) Create an identity column with specified sequence options (PostgreSQL)
->always() Defines the precedence of sequence values over input for an identity column (PostgreSQL)


How to fetch data

$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}


here User is the Model name and with() is the function to pass database table name and finally get() method is get all data of table.

what is with()

with() return the model object and its related results.
with() is for eager loading the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

what is has()

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

what is WhereHas()

$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Note :

Order::with('orderItems')->get();
Laravel change this code to only two SQL:

// get all orders:
SELECT * FROM orders;

// get the order_items based on the orders' id above
SELECT * FROM order_items WHERE order_items.order_id IN (1,2,3,4...);

And then laravel merge the results of the second SQL as different from the results of the first SQL by foreign key. At last return the collection results.

So if you selected columns without the foreign_key in closure, the relationship result will be empty:

Order::with(['orderItems' => function($query) {
// $query->sum('quantity');
$query->select('quantity'); // without `order_id`
}
])->get();

#=> result:
[{ id: 1,
code: '00001',
orderItems: [], // <== is empty
},{
id: 2,
code: '00002',
orderItems: [], // <== is empty
}...
}]

Has

Has will return the model's object that its relationship is not empty.

Order::has('orderItems')->get();
Laravel change this code to one SQL:

select * from `orders` where exists (
select * from `order_items` where `order`.`id` = `order_item`.`order_id`
)

whereHas

whereHas and orWhereHas methods to put where conditions on your has queries. These methods allow you to add customized constraints to a relationship constraint.

Order::whereHas('orderItems', function($query) {
$query->where('status', 1);
})->get();
Laravel change this code to one SQL:

select * from `orders` where exists (
select *
from `order_items`
where `orders`.`id` = `order_items`.`order_id` and `status` = 1
)

Modifying Columns

Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the required adjustments

composer require doctrine/dbal

Updating Column Attributes

The change method allows you to modify type and attributes of existing columns. For example, you may wish to increase the size of a string column.

Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->change();
});

We could also modify a column to be nullable:

Schema::table('users', function (Blueprint $table) {
$table->string('name', 50)->nullable()->change();
});

Renaming Columns

To rename a column, you may use the renameColumn method on the schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

Schema::table('users', function (Blueprint $table) {
$table->renameColumn('from', 'to');
});

Dropping Columns

To drop a column, use the dropColumn method on the schema builder. Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library:

Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});

You may drop multiple columns from a table by passing an array of column names to the dropColumn method:


Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['votes', 'avatar', 'location']);
});



Command Description
$table->dropMorphs('morphable'); Drop the morphable_id and morphable_type columns.
$table->dropRememberToken(); Drop the remember_token column.
$table->dropSoftDeletes(); Drop the deleted_at column.
$table->dropSoftDeletesTz(); Alias of dropSoftDeletes() method.
$table->dropTimestamps(); Drop the created_at and updated_at columns.
$table->dropTimestampsTz(); Alias of dropTimestamps() method.


Adding Indexes

The Laravel schema builder supports several types of indexes. The following example creates a new email column and specifies that its values should be unique. To create the index, we can chain the unique method onto the column definition

$table->string('email')->unique();


Alternatively, you may create the index after defining the column. For example:
$table->unique('email');


Available Index Types

Each index method accepts an optional second argument to specify the name of the index

$table->primary('id'); Adds a primary key.
$table->primary(['id', 'parent_id']); Adds composite keys.
$table->unique('email'); Adds a unique index.
$table->index('state'); Adds a plain index.
$table->spatialIndex('location'); Adds a spatial index. (except SQLite)

Dropping Indexes

To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the indexed column, and the index type.

$table->dropPrimary('users_id_primary'); Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique'); Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index'); Drop a basic index from the "geo" table.
$table->dropSpatialIndex('geo_location_spatialindex'); Drop a spatial index from the "geo" table (except SQLite).

Foreign Key Constraints

Laravel support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table

Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');

$table->foreign('user_id')->references('id')->on('users');
});

Schema::table('posts', function (Blueprint $table) { $table->foreignId('user_id')->constrained(); });

The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced.


drop a foreign key

To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:

$table->dropForeign('posts_user_id_foreign');





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial