Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get database field type in Laravel?

Is there a way to get the datatype of a database table field? This would be almost like the inverse of a migration.

For example, if the migration of a users table column looks like

... $table->integer('age') ... 

Is there a function that will return integer if I specify table user and column age?

I'm not interested in a specific database implementation, (mysql_field_type()). Like Laravel's migration, it needs to be database agnostic.

like image 470
Hao Luo Avatar asked Sep 01 '13 20:09

Hao Luo


People also ask

How do I change the datatype of a column in Laravel migration?

How to change data type of column in laravel 9 migration ? Step 1 : Install doctrine/dbal package. Step 2 : Generate migration file. Step 3 : Open generated migration file and update.

What is foreign key in Laravel?

A foreign key is a field that is used to establish the relationship between two tables via the primary key (You can also use a non-primary field but not recommended). In this tutorial, I show how you can add a foreign key constraint while creating a table using migration in the Laravel 8 project.05-May-2022.

What is seeder in Laravel?

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

What is unsigned integer Laravel?

Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.


2 Answers

For Laravel 4:

After digging in Laravel, this is what I got.

DB::connection()->getDoctrineColumn('users', 'age')->getType()->getName()

like image 130
Hao Luo Avatar answered Oct 13 '22 05:10

Hao Luo


For Laravel 5.2 - 9.x

use Illuminate\Database\Schema\Builder::getColumnType()

DB::getSchemaBuilder()->getColumnType($tableName, $colName) 

e.g.

$ageType = DB::getSchemaBuilder()->getColumnType('user', 'age') 

You may need to run this command if you haven't already:

composer require doctrine/dbal 
like image 33
Sᴀᴍ Onᴇᴌᴀ Avatar answered Oct 13 '22 06:10

Sᴀᴍ Onᴇᴌᴀ