How do Laravel Eloquent Model Attributes map to a table?


Eloquent is a new object relational mapper (ORM) that helps to interact with databases. With Eloquent each table has a mapping Model that takes care of all the operations on that table.

Model in Laravel represents the table in the database. For example, if you have table customers, the model name will be customer, for users it will be user, employees it will be employee. The table name has to be plural and the model name has to be singular. This is a pattern followed, but that does not stop you from using the naming convention of your choice for table name and model name.

Before starting working with a model, make sure you are connected to the database. The database configuration is available inside config/database.php. Also the .env file has the details of database connection.

In this example we are going to make use of the mysql database, so in .env file we have the following environment variables with values.

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

Inside config/database.php, the above environment variables are used –

'mysql' => [
   'driver' => 'mysql',
   'url' => env('DATABASE_URL'),
   'host' => env('DB_HOST', '127.0.0.1'),
   'port' => env('DB_PORT', '3306'),
   'database' => env('DB_DATABASE', 'forge'),
   'username' => env('DB_USERNAME', 'forge'),
   'password' => env('DB_PASSWORD', ''),
   'unix_socket' => env('DB_SOCKET', ''),
   'charset' => 'utf8mb4',
   'collation' => 'utf8mb4_unicode_ci',
   'prefix' => '',
   'prefix_indexes' => true,
   'strict' => true,
   'engine' => null,
   'options' => extension_loaded('pdo_mysql') ? array_filter([
      PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
   ]) : [],
],

We will first create a model using the below command −

php artisan make:model User

The output of the command is −

C:\xampp\htdocs\laraveltest>php artisan make:model User
Model created successfully.
C:\xampp\htdocs\laraveltest>

Once the command is executed you will get the model file in app/Models/User.php

<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable{ use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', ]; }

Now create a controller to work with User Model. The command to create controller is as follows −

php artisan make:controller UserController

The output on execution of above command is −

C:\xampp\htdocs\laraveltest>php artisan make:controller UserController
Controller created successfully.
C:\xampp\htdocs\laraveltest>

Open UserController.php file and include User model as shown below −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ // }

Now first add a route inside routes/web.php as shown below −

use App\Http\Controllers\UserController;
Route::get('users', [UserController::class, 'index']);

Inside your UserController.php add a method index() in that we can query the table. Now to get the Model attributes mapped to table you can get the column name using the data from the table.

Example 1

In this example we are using User::find(1), here 1 is the primary key value passed to find, i.e. the id of the users table.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $user = User::find(1); print_r($user->getAttributes()); } }

Output

The output will give you details of the table attributes along with data for the id:1.

Array(
   [id] => 1
   [name] => 3qULmjwzo1
   [email] => zt6EovRjV7@gmail.com
   [email_verified_at] =>
   [password] => yhka61wZeS
   [remember_token] =>
   [created_at] =>
   [updated_at] =>
)

Example 2

Now, if the table has no data you can try the following example to get the table attributes −

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class UserController extends Controller{ public function index() { $user = User::first(); $table_columns = array_keys(json_decode($user, true)); print_r($table_columns); } }

Output

The output of the above code is −

Array(
   [0] => id
   [1] => name
   [2] => email
   [3] => email_verified_at
   [4] => created_at
   [5] => updated_at
)

Updated on: 30-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements