How to Use Database Eloquent in Slim

in utopian-io •  7 years ago  (edited)

download.jpg

image source

In this tutorial I will share the tutorial how to use eloquent database system, for you who are not familiar with this database system. Eloquent is a database system used by the laravel framework, but it's okay to use it outside laravel including in PHP Native and of course in Microframework Slim. for those of you who have never known, you can see it at https://laravel.com/docs/5.6/eloquent. there are so many advantages we can get by using eloquent. this database system may be your choice to use it in Microframework Slim. let's get started.

What Will I Learn?

  • Install Package With Composer
  • Setting Database for Eloquent
  • Create Container Database

Requirements

  • Install Slim
  • Localhost : Xampp, Wampp or etc
  • Php intermediate

Difficulty

  • Intermediate

Install Package Eloquent

The first step we have to install Eloquent in our Slim application using the help of composer :
composer require illuminate/database

Screenshot_14.png

Setting Database

After finish installing Eloquent then we have to do the setting on our Slim application, I have an index.php file with this structure


<?php
require __DIR__ .'./vendor/autoload.php';
$app = new Slim\App([
        'settings' =>[
            'displayErrorDetails' => true,
            'db'=>[
                'driver'    => 'mysql',
                'host'      => 'localhost',
                'database'  => 'tutorial',
                'username'  => 'root',
                'password'  => '',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ]
        ]
]);
$container = $app->getContainer();
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig( __DIR__ .'/templates', [
        'cache' => 'path/to/cache'
    ]);
    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $container['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container['router'], $basePath));
    return $view;
};
$container['db'] = function ($container) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($container['settings']['db']);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    return $capsule;
};
$app->get('/forum',function($request,$response,$args){
    var_dump($this->db->table('berita')->get());
});
$app->run();

I have installed Twig as its templating, and using a routing system, to know the system templating and routing system, you can see it in the curriculum that I have created in the curriculum below.

Setting Database


$app = new Slim\App([
        'settings' =>[
            'displayErrorDetails' => true,
            'db'=>[
                'driver'    => 'mysql',
                'host'      => 'localhost',
                'database'  => 'tutorial',
                'username'  => 'root',
                'password'  => '',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ]
        ]
]);

This is a setting to connect to the database, we wrap all the keys and values ​​into an array named 'db'=> [] :
  • 'drive' => 'mysql'
  • : We use Mysql for the database
  • 'host' => 'localhost'
  • : We use localhost to run localserver
  • 'database' => 'tutorial'
  • : The name of database, in this case the name is tutorial
  • 'username' => 'root'
  • : Username of Mysql Connection database, in this case the name is root
  • 'password' => ''
  • : Username of Mysql Connection database, in this case the password is empty .

    Create Container Database

    We have made a setting to connect to our database, next to use our database in Slim application that we make, we must make it in a container. Still in the same index.phpfile, here is how make it:

    
    $container['db'] = function ($container) {
        $capsule = new \Illuminate\Database\Capsule\Manager;
        $capsule->addConnection($container['settings']['db']);
        $capsule->setAsGlobal();
        $capsule->bootEloquent();
        return $capsule;
    };
    
    
    $container['db'] :We create a key from container with db name, so later if we want to access function in container db, we will use it like this $this->db .
    $capsule = new \Illuminate\Database\Capsule\Manager; : This is the namespace system of the eloquent package.
    $capsule->addConnection($container['settings']['db']); : Connect the connections we have wrapped in the 'db' array, which is in the settings.
    $capsule->setAsGlobal(); : Set Connection as Global , So you can access anywhere in the slim apikasi we have created.
    $capsule->bootEloquent(); :To run eloquent

    after finished creating the container, we can test whether the connection kedatabase we succeed, if successful then we will see the data residing in database. We can test in routing / forum.

    
    $app->get('/forum',function($request,$response,$args){
        var_dump($this->db->table('berita')->get());
    });
    
    
    $this->db->table('berita')->get() : Eloquent method to retrieve all data in the database . I will var_dump to see its results.

    Screenshot_15.png

    Screenshot_16.png

    If not a mistake we will see the data in our database Tutorial appears in the routing /forum.
    And I'll use a little eloquent method to pull data like a regular mysql query.
    Display based on id we want :
    $this->db->table('berita')->where('id',15)->get() : I will only show data only id 15.

    Screenshot_17.png

    We have successfully connected to the database in Slim framework and we have also used Eloquent in Slim. We have also made Eloquent in the Container so we can use Eloquent anywhere in the Slim application that we created, Just so many tutorials this time, may be useful and I hope you keep trying to get to know other Eloquent functions, Thank you :)

    Curriculum



    Posted on Utopian.io - Rewarding Open Source Contributors

    Authors get paid when people like you upvote their post.
    If you enjoyed what you read here, create your account today and start earning FREE STEEM!
    Sort Order:  

    Thank you for the contribution. It has been approved.

    You can contact us on Discord.
    [utopian-moderator]

    1UP-Kayrex_tiny.png

    You've got upvoted by Utopian-1UP!

    You can give up to ten 1UP's to Utopian posts every day after they are accepted by a Utopian moderator and before they are upvoted by the official @utopian-io account. Install the @steem-plus browser extension to use 1UP. By following the 1UP-trail using SteemAuto you support great Utopian authors and earn high curation rewards at the same time.


    1UP is neither organized nor endorsed by Utopian.io!

    Hey @alfarisi94 I am @utopian-io. I have just upvoted you!

    Achievements

    • You have less than 500 followers. Just gave you a gift to help you succeed!
    • Seems like you contribute quite often. AMAZING!

    Suggestions

    • Contribute more often to get higher and higher rewards. I wish to see you often!
    • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

    Get Noticed!

    • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

    Community-Driven Witness!

    I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

    mooncryption-utopian-witness-gif

    Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x