php - Laravel sounds like magic

684

I just recently started experimenting with laravel, lovely. One thing l dont understand though is how laravel knows my table l just added a model and the model isnt the exact table name, but just how does it manage to get my table,

845

Answer

Solution:

Reference to Eloquent Model Conventions:

Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified.

Internally, Laravel does something like this.

$table = $table ?: Str::plural($name);

So it will automatically try to look for the plural of your model name if no$table property is being set.

870

Answer

Solution:

Laravel follows a Naming convention for Eloquent Classes and Tables.

From Laravel Website | Eloquent: Getting Started

Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.

Eg.

ClassUser will by default refers to Mysql Tableusers (Camel Case to Snake Case and Plural).

ClassNotificationsLog will by default refers to Mysql Tablenotifications_logs (Camel Case to Snake Case and Plural).

But if you don't want to follow the convention then you can Mention the table name explicitly

Eg. If I want my ClassPlane should refers toflights table in Database then following code will work

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plane extends Model
{
     /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'flights';
}
195

Answer

Solution:

Actually the when you make a model it automatically make a table with it's plural you could change this by added the following code in the model

protected $table= 'table_name';

Please also check the name in the migration it should be same as the name you mentioned in the model class because it might show error while using eloquent class functions due to different table names

People are also looking for solutions to the problem: PHP taking an array of objects, get rid of the duplicates one

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.