Things to know in Laravel : chapter one

Introduction

Ever wondered how Laravel finds the database tables when we follow singular naming convention for Model ? If you’re then you have come to the right place . First, we all love laravel 😎 . Let’s talk something about laravel before we start.

Well, for speeding up development process, laravel does many things under the hood and hence we don’t have to worry about many things like Auth scaffolding, CLI commands for generating migrations, Resource controllers, Models and many other things. These all help us speed up our development process.

Getting Started

Laravel comes in with fast and convenient way for creating database and handling it. With migration version control, laravel is amazing. If you’re not new to laravel, you might already know about migration and not new to commands like :

php artisan make:migration create_tablename_table

php artisan migrate:refresh

php artisan migrate:rollback

The first commands will create migration table. The second one will refresh your migrations. The last one will rollback your database. Anyways, right now we will be talking this much about migrations and their commands.

Let’s say we create a model along with its corresponding migration using the command :

php artisan make:model User -m

This will create a migration table for model User. Whenever we need to fetch data from database , we use syntax like :

App\User::all();

This will get all the rows from your database “users”. Even though we never did mention User model about our database name “users”, somehow the model finds out the table itself and fetch the data for us. Amazing right 😎 ?

Now how did model “User” find table “users” ?

Every laravel model have to extend Illuminate\Database\Eloquent\Model. Go to the Illuminate\Database\Eloquent\Model , you can see a function name getTable().

Illuminate\Support\Str::plural() method uses Illuminate\Support\Pluralizer and Pluralizer extends Doctrine\Common\Inflector\Inflector. This is where all the magic happens.

If you look into the inflector class, you can find basic rules for both plural and singular form. There are many functions you can look into it.

Laravel have helper functions like str_plural() and str_singular(). We can use them in our projects, if we ever face these type of scenario.

str_plural()

As name implies, this function converts a string to its plural form. A simple demonstration :

str_plural(‘user’); // will result to “users”

str_singular()

This function convert a string to its singular form. Now if you pass “users” as a parameter, it will result to “user”.

str_singular(‘users’); // will result to “user”

We can use these functions. These functions currently only supports the English language.

Sharing is caring!

Related Post