Eloquent is an Object Relational Mapper (ORM) present in the Laravel Framework. Laravel Eloquent provide easy way to interect with database. With the help of Laravel Eloquent ORM we can facilitate database record manipulation by presenting the data as an object. We can perform operations like insert,update,delete and also fetch records from database table.

Example of laravel eloquent ORM

First we need to create laravel Model Post.

Commond – php artisan make:model Post.

app/models/Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [];
}

Create Laravel Controller where we can use our model.

Commond – php artisan make:controller PostController.

app/Http/PostController.php

Datetime Eloquent –

Datetime eloquent is used to retrieve records from a table by a specific day, month or year. So here we explain how to get the record.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    function viewPost(){
     // Date Wise
     Post::whereDate('created_at','2020-08-04')->get(); 
     
     //Month Wise
     Post::whereMonth('created_at',08)->get();

     //Day Wise
     Post::whereDay('created_at',08)->get();

     //Year Wise
     Post::whereYear('created_at',2020)->get();

     //Time Wise
     Post::whereTime('created_at','15:24:50')->get();

    }
}

First Eloquent – Get only single row

First method is used to get only single record from table.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
    function viewPost(){
      Post::where('url','=','Test')->first();
      Post::where('url','=','Test')->last();
    }
}

Find Eloquent

<?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Models\Post;

class PostController extends Controller
{
    function viewPost(){
      Post::find(1);
      Post::find([1,2,3]);
      Post::find(1,['name','title','message']);
      Post::find([1,2,3],['name','title','message'])->first();
      Post::find([1,2,3],['name','title','message'])->last();
      Post::where('email','demo@gmail.com')->get(); //for all records
      Post::where('email','demo@gmail.com')->first(); //1 records
      Post::whereEmail('demo@gmail.com')->first(); //1 records with X method
    }
}

Other additional relevant articles.

Multilevel drag and drop menu in laravel

Send email with attachment from gmail in laravel using form

Jquery Validation in Laravel 8

By admin

Leave a Reply

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