Using Illuminate without Laravel

If you have read past posts you know that I have decided to build a movie indexing app for personal use to make searching and finding movies I own easier. I decided to use just the Illuminate database component that Laravel uses to handle the CRUD.

First step, pull it in (I used composer).

{
    "name" : "name of app",
    "description" : "Desc of app",
    "license" : "MIT",
    "require" : {
        "illuminate/database": "*"
    }
}

Setting up the database connection is relatively easy if you use the docs on the Github and Laravel as a guide.

$config = array(
    'db' => array(
        'driver' => 'mysql',
        'host' => '127.0.0.1',
        'database' => 'imdb',
        'username' => 'username',
        'password' => 'password',
        'collation' => 'utf8_general_ci',
        'charset' => 'utf8',
        'prefix' => 'imdb_',
        'port' => ''
    )
);

$connFactory = new \Illuminate\Database\Connectors\ConnectionFactory(new \Illuminate\Container\Container());
$conn = $connFactory->make($config['db']);
$resolver = new \Illuminate\Database\ConnectionResolver();
$resolver->addConnection('default', $conn);
$resolver->setDefaultConnection('default');
\Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver);

Then all you really need to do is create your class file:

<?php
namespace ProjectName\Models;

use Illuminate\Database\Eloquent\Model;

class Movie extends Model {
    protected $fillable = array('title', 'release_date');
    protected $guarded = array('id', 'updated_at', 'created_at');
}

You can easily add a record to the database by doing:

$movie = new Movie(array('title' => A movie title, 'release_date' => '2014-01-23'));
$movie->save();

Nice and quick to get rolling so you aren’t spending so much time on the repetitive task of CRUD for each model.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>