Eloquent is an ORM(object relational model) used to interact with database by providing a model for each database table.

Creating model:

php artisan make:model owner -mc
php artisan make:model house -mc

Here M is for model and c is for controller. Let’s check our owner model class at apps/model

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class owner extends Model
{
    use HasFactory;
}

So where is our table name? By default owner model is expecting the table name  “owners” .But we can use any table here

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class owner extends Model
{
    use HasFactory;
    protected $table='owners';        
}

 

Primary Key:

The default primary key for each table is “id” for eloquent but we can change it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class owner extends Model
{
    use HasFactory;
    protected $table='owners';
    protected $primaryKey='owner_id';
}

if wish not to increment the primary key value we have to set

class owner extends Model
{
    use HasFactory;
    public $incrementing=false;

}

Also if our primary is not an integer

class owner extends Model
{
    use HasFactory;
    public $keyType='string';

}

Note: Composite primary key is not supported in eloquent.   

Lets get all result from controller using a model in elequent

class TestEqlController extends Model
{
    use HasFactory;

    public function index()
    {
        $house=house::all();

        foreach ($house as $hou)
        {
            echo $hou->house_name;
        }
    }
}

Building Query: eloquent models are query builder as well

$house=house::where('id',1)
    ->orderBy('id')
    ->take(1)
    ->get();
dd($house);

 

By Navid Anjum

Full-stack web developer and founder of Laravelaura. He makes his tutorials as simple as humanly possible and focuses on getting the students to the point where they can build projects independently. https://github.com/NavidAnjum

One thought on “Learning Eloquent with Laravel 8”

Leave a Reply

Your email address will not be published. Required fields are marked *