Use Eloquent ORM in PHP projects without Laravel
-
When talking about Laravel Framework, Eloquent is a one of best part of the framework, have you ever thought of using Eloquent without entire Laravel framework? In this post i'm teaching you how to use Eloquent ORM without Laravel Framework, i'll create simple form using Eloquent. Let's dive,
Required Environment
- Windows/Mac or Linux
- Apache server
- PHP 7+
Setting up Eloquent in PHP
First move to empty folder on public directory and run below command on terminal.
composer require illuminate/database
This will generate
composer.json
and installeloquent
dependency on our project directory.After command successful, create a new file and name it
bootstrap.php
and put below code in it,<?php require "vendor/autoload.php"; use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; // Mysql serve credentials $capsule->addConnection([ "driver" => "mysql", "host" =>"127.0.0.1", "database" => "ums", "username" => "root", "password" => "123" ]); // Making Capsule instance available globally $capsule->setAsGlobal(); // Booting the Eloquent ORM $capsule->bootEloquent();
The code requiring composer autoload class and importing Eloquent Manager and making it's instance called
$capsule
. In next line we setting database connection and making it available globally using$capsule
instance, finally we're booting the Eloquent ORM.After this create a database on your localhost and name it ums
Creating Migrations
Migration is used to build your application database schema, in Laravel we use artisan commands to generate migrations and run them, so let's see how we can use migrations without Laravel Framework and artisan commands.
Now create a folder called
database
and createuser_table_migration.php
inside the newly created folder and put below code<?php require "../bootstrap.php"; use Illuminate\Database\Capsule\Manager as Capsule; Capsule::schema()->create('users', function ($table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); });
You can see a some similarity of this code and what we would write in Laravel, the difference is the
schema
is reference fromCapsule
class.Now our migration for
users
table is ready, to run this migration simply openuser_table_migration.php
file on browser if you see a blank page, it means script executed successfully, to verify check your database, there should beusers
table created.Note - Since these migration scripts publicly available, this is not suitable for Production use
Creating Models
Let's see how we implement Eloquent Models, first create a new folder and name it models, then open
composer.json
and edit it like below code{ "require": { "illuminate/database": "^7.5" }, "autoload": { "classmap": [ "models" ] } }
This will add our models folder as autoload, now create a new file inside models folder and name it
User.php
<?php use Illuminate\Database\Eloquent\Model as Eloquent; class User extends Eloquent { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', ]; }
Now our Eloquent Models are ready to use, let's create form to insert data.
Create a new file in the root of the project and name it
index.php
, then put below code<?php session_start(); $error = isset($_SESSION['error']) ? $_SESSION['error']:true; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create User</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <style> #bg-cover { background-size: cover; height: 100%; text-align: center; display: flex; align-items: center; position: relative; } #bg-cover-caption { width: 100%; position: relative; z-index: 1; } /* background overlay */ form:before { content: ''; height: 100%; left: 0; position: absolute; top: 0; width: 100%; background-color: rgba(0,0,0,0.3); z-index: -1; border-radius: 10px; } </style> </head> <body> <section id="bg-cover" class="min-vh-100"> <div id="bg-cover-caption"> <div class="container"> <div class="row text-white"> <div class="col-xl-5 col-lg-6 col-md-8 col-sm-10 mx-auto text-center form p-4"> <h1 class="display-4 py-2 text-truncate">Create User</h1> <div class="px-2"> <form action="save_user.php" method="POST" class="justify-content-center"> <div class="form-group"> <label class="sr-only">Name</label> <input type="text" name="name" class="form-control" placeholder="Name" required> </div> <div class="form-group"> <label class="sr-only">Email</label> <input type="email" name="email" class="form-control" placeholder="Email" required> </div> <div class="form-group"> <label class="sr-only">Password</label> <input type="password" name="password" class="form-control" placeholder="Password" required> </div> <button type="submit" class="btn btn-primary btn-lg">Create</button> <?php if ($error == false) { echo '<span>User added</span>'; } ?> </form> </div> </div> </div> </div> </div> </section> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html>
Here i'm using bootstrap for frontend, now our form is ready. Then we need another php script to handle form submit so create another file and name it
save_user.php
and put below code,<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); session_start(); require "bootstrap.php"; $name = $_POST['name']; $email = $_POST['email']; $password = password_hash($_POST['password'], PASSWORD_BCRYPT); $user = User::create([ 'name' => $name, 'email' => $email, 'password' => $password, ]); $_SESSION['error'] = false; header('Location: index.php');
This will handle our form submit event and insert the data to database using Eloquent. Finally open your terminal and run below command,
composer dump-autoload -o
This will generate optimised autoload files for our project. Now open
index.php
from browser and enter some info into form and see what happened.Project files can found here
-
great ORM in the world. thanks keep it up
-
@root welcome bro
-
thanks bro