How Eloquent save lives of most of PHP Developers

May 24, 2017 By - Usama Muneer | 317
    eloquent

    Introducing Eloquent


    If you guys haven’t ever taste the aroma of Laravel’s ORM Eloquent, than this article is for you, believe me. I’ll take you through the crazy ride starting from building queries with full of hurdles as in the procedural PHP, bump into fetching data the OO(Object-oriented) way and then move straight towards the awesomeness of Eloquent & you’ll see why most of the developers fell in love with these piece of greatness which Laravel have brought in PHP.

    Diving in

    So let’s get started with an assumption that you’ve already setup your database schema let’s say “testSchema” and it contains a table let’s say “products”. We’ll play around with this piece of information in each step.

    If you’re reading this then I’m sure, most of you have at least some experience of working with PHP, as this is not for the very beginners.

    Procedural PHP

    So How do you create a Database Connection in procedural PHP?

    you need to remember some compulsory PHP functions to create a connection and then make queries to the Database. Some of those functions include:

    mysqli_connect();
     mysqli_query();
     mysqli_fetch_assoc();
     mysqli_connect_error();

    And all of there parameters, which is quite disturbing and frustrating for the most of the developers to remember. So let’s create a connection file and see how it looks like.

    <?php 
    $server_name = 'localhost';
    
    $username = 'root';
    $password = 'root';
    $db_name = 'testSchema';
    
    $connection = mysqli_connect($server_name,$username,$password, $db_name);
    
    //check if its connected
    
    if(mysqli_connect_error()) {
      $logMessage = 'MYSQL Error: . mysqli_connect_error();
      die('could not connect to the Database');}
    
    //if connection successful, 
    //query
    
    $query = mysqli_query($connection,"SELECT * FROM products WHERE ID = $ID");
     
    //fetch the information from the Database
    $product = mysqli_fetch_assoc($query);
    ?>

    Alright, this seems so complex to write these set of code each time you wanted to connect to a Database. So the next question arise in most of Developer’s mind is “Will this thing gets easier with OOP?” Well let’s find out ourselves.

    Object Oriented Way

    <?php
    class Product
    {
        public function __construct( mysqli $connection )
        {
            $this->connection = $connection;
        }
    
        public function get( $id )
        {
            return $this->connection
                ->query("SELECT * FROM products WHERE id = " . $id)
                ->fetch_assoc();
        }
    }
    
    # Usage --> Get Product by ID == $ID
    $db = new mysqli('localhost','root','root','testSchema');
    
    $product = new Product($db);
    $product->get($ID);​

    I’m sure this ride is getting bumpier & uneven as you have came along. But I assure you with this final reveal of how Eloquent fetches the Data from the Database will surely get you a relief.

    Eloquent way


    Assume the connection has been setup already & our Product model is configured in our Laravel’s application, if you’re somewhat familiar. We’ll just look through how we call it to fetch the required information.

    <?php 
     
    $product = App\Product::find($ID);

    Well That’s it, this is how easier it could be done with just a single line of code. This is the beauty of Eloquent ORM where each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

    I hope you’ve enjoyed reading this article, if you want to know more about Laravel and it’s features, then I would recommend you to stay connected.

    You can also follow me on Twitter.

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    No Related Posts Found