<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Use Eloquent ORM in PHP projects without Laravel]]></title><description><![CDATA[<p dir="auto">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,</p>
<p dir="auto"><strong>Required Environment</strong></p>
<ul>
<li>Windows/Mac or Linux</li>
<li>Apache server</li>
<li>PHP 7+</li>
</ul>
<p dir="auto"><strong>Setting up Eloquent in PHP</strong></p>
<p dir="auto">First move to empty folder on public directory and run below command on terminal.</p>
<p dir="auto"><code>composer require illuminate/database</code></p>
<p dir="auto">This will generate <code>composer.json </code>and install <code>eloquent</code> dependency on our project directory.</p>
<p dir="auto">After command successful, create a new file and name it <code>bootstrap.php</code> and put below code in it,</p>
<pre><code>&lt;?php

require "vendor/autoload.php";

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

// Mysql serve credentials
$capsule-&gt;addConnection([
   "driver" =&gt; "mysql",
   "host" =&gt;"127.0.0.1",
   "database" =&gt; "ums",
   "username" =&gt; "root",
   "password" =&gt; "123"
]);

// Making Capsule instance available globally
$capsule-&gt;setAsGlobal();

// Booting the Eloquent ORM
$capsule-&gt;bootEloquent();
</code></pre>
<p dir="auto">The code requiring composer autoload class and importing <strong>Eloquent Manager</strong> and making it's instance called <code>$capsule</code>. In next line we setting database connection and making it available globally using <code>$capsule</code> instance, finally we're booting the <strong>Eloquent ORM</strong>.</p>
<p dir="auto">After this create a database on your localhost and name it <strong>ums</strong></p>
<p dir="auto"><strong>Creating Migrations</strong></p>
<p dir="auto">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.</p>
<p dir="auto">Now create a folder called <code>database</code> and create <code>user_table_migration.php</code> inside the newly created folder and put below code</p>
<pre><code>&lt;?php

require "../bootstrap.php";

use Illuminate\Database\Capsule\Manager as Capsule;

Capsule::schema()-&gt;create('users', function ($table) {
    $table-&gt;increments('id');
    $table-&gt;string('name');
    $table-&gt;string('email')-&gt;unique();
    $table-&gt;string('password');
    $table-&gt;timestamps();
});
</code></pre>
<p dir="auto">You can see a some similarity of this code and what we would write in Laravel, the difference is the <code>schema</code> is reference from <code>Capsule</code> class.</p>
<p dir="auto">Now our migration for <code>users</code> table is ready, to run this migration simply open  <code>user_table_migration.php</code> file on browser if you see a blank page, it means script executed successfully, to verify check your database, there should be <code>users</code> table created.</p>
<p dir="auto"><strong>Note - Since these migration scripts publicly available, this is not suitable for Production use</strong></p>
<p dir="auto"><strong>Creating Models</strong></p>
<p dir="auto">Let's see how we implement <strong>Eloquent Models</strong>, first create a new folder and name it <strong>models</strong>, then open <code>composer.json</code> and edit it like below code</p>
<pre><code>{
    "require": {
        "illuminate/database": "^7.5"
    },
    "autoload": {
        "classmap": [
            "models"
        ]
    }
}
</code></pre>
<p dir="auto">This will add our models folder as autoload, now create a new file inside <strong>models</strong> folder and name it <code>User.php</code></p>
<pre><code>&lt;?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',
   ];
 }
</code></pre>
<p dir="auto">Now our Eloquent Models are ready to use, let's create form to insert data.</p>
<p dir="auto">Create a new file in the root of the project and name it <code>index.php</code>, then put below code</p>
<pre><code>&lt;?php
    session_start();

    $error = isset($_SESSION['error']) ? $_SESSION['error']:true;
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Create User&lt;/title&gt;

    &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"&gt;

    &lt;style&gt;
        #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;
        }
    &lt;/style&gt;
&lt;/head&gt;
    &lt;body&gt;
        &lt;section id="bg-cover" class="min-vh-100"&gt;
            &lt;div id="bg-cover-caption"&gt;
                &lt;div class="container"&gt;
                    &lt;div class="row text-white"&gt;
                        &lt;div class="col-xl-5 col-lg-6 col-md-8 col-sm-10 mx-auto text-center form p-4"&gt;
                            &lt;h1 class="display-4 py-2 text-truncate"&gt;Create User&lt;/h1&gt;
                            &lt;div class="px-2"&gt;
                                &lt;form action="save_user.php" method="POST" class="justify-content-center"&gt;
                                    &lt;div class="form-group"&gt;
                                        &lt;label class="sr-only"&gt;Name&lt;/label&gt;
                                        &lt;input type="text" name="name" class="form-control" placeholder="Name" required&gt;
                                    &lt;/div&gt;
                                    &lt;div class="form-group"&gt;
                                        &lt;label class="sr-only"&gt;Email&lt;/label&gt;
                                        &lt;input type="email" name="email" class="form-control" placeholder="Email" required&gt;
                                    &lt;/div&gt;
                                    &lt;div class="form-group"&gt;
                                        &lt;label class="sr-only"&gt;Password&lt;/label&gt;
                                        &lt;input type="password" name="password" class="form-control" placeholder="Password" required&gt;
                                    &lt;/div&gt;

                                    &lt;button type="submit" class="btn btn-primary btn-lg"&gt;Create&lt;/button&gt;

                                    &lt;?php
                                        if ($error == false) {
                                            echo '&lt;span&gt;User added&lt;/span&gt;';
                                        }
                                    ?&gt;
                                &lt;/form&gt;
                            &lt;/div&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/section&gt;
        
        &lt;script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"&gt;&lt;/script&gt;
        &lt;script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"&gt;&lt;/script&gt;
        &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p dir="auto">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 <code>save_user.php</code> and put below code,</p>
<pre><code>&lt;?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' =&gt; $name,
    'email' =&gt; $email,
    'password' =&gt; $password,
]);

$_SESSION['error'] = false;

header('Location: index.php');
</code></pre>
<p dir="auto">This will handle our form submit event and insert the data to database using Eloquent. Finally open your terminal and run below command,</p>
<p dir="auto"><code>composer dump-autoload -o</code></p>
<p dir="auto">This will generate optimised autoload files for our project. Now open <code>index.php</code> from browser and enter some info into form and see what happened.</p>
<p dir="auto">Project files can found <a href="https://github.com/codingwithmrdev/php-eloquent" target="_blank" rel="noopener noreferrer nofollow ugc">here</a></p>
]]></description><link>https://lankadevelopers.lk/topic/557/use-eloquent-orm-in-php-projects-without-laravel</link><generator>RSS for Node</generator><lastBuildDate>Mon, 20 Jul 2026 18:58:08 GMT</lastBuildDate><atom:link href="https://lankadevelopers.lk/topic/557.rss" rel="self" type="application/rss+xml"/><pubDate>Thu, 09 Apr 2020 19:24:35 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Use Eloquent ORM in PHP projects without Laravel on Tue, 14 Apr 2020 03:30:32 GMT]]></title><description><![CDATA[<p dir="auto">thanks bro</p>
]]></description><link>https://lankadevelopers.lk/post/3283</link><guid isPermaLink="true">https://lankadevelopers.lk/post/3283</guid><dc:creator><![CDATA[Nubelle]]></dc:creator><pubDate>Tue, 14 Apr 2020 03:30:32 GMT</pubDate></item><item><title><![CDATA[Reply to Use Eloquent ORM in PHP projects without Laravel on Fri, 10 Apr 2020 05:53:33 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="https://lankadevelopers.lk/uid/27">@root</a> welcome bro</p>
]]></description><link>https://lankadevelopers.lk/post/3269</link><guid isPermaLink="true">https://lankadevelopers.lk/post/3269</guid><dc:creator><![CDATA[dev_lak]]></dc:creator><pubDate>Fri, 10 Apr 2020 05:53:33 GMT</pubDate></item><item><title><![CDATA[Reply to Use Eloquent ORM in PHP projects without Laravel on Thu, 09 Apr 2020 21:08:56 GMT]]></title><description><![CDATA[<p dir="auto">great ORM in the world. thanks keep it up</p>
]]></description><link>https://lankadevelopers.lk/post/3268</link><guid isPermaLink="true">https://lankadevelopers.lk/post/3268</guid><dc:creator><![CDATA[root]]></dc:creator><pubDate>Thu, 09 Apr 2020 21:08:56 GMT</pubDate></item></channel></rss>