Laravel query builder outside of Laravel

Lekker
2 min readOct 20, 2015

--

http://www.laravel.com

While we do love the Laravel framework, sometimes building from scratch is best. When going that route you are free to build your system using your own code and only bringing in the outside scripts that are truly required and will be utilized by your system which allows for freeing up resources.

We wanted to share an easy way to utilize their features on your own system while not implementing their entire framework.

Step 1.
- Install Composer package manager( https://getcomposer.org )
- With Composer install: “illuminate/database
illuminate/events
illuminate/container

Step 2.
- Create an empty class extending the Capsule\Manager for the db connection

class db extends Illuminate\Database\Capsule\Manager{}

Step 3.
- Initialize the connection

$capsule = new db;
$capsule->addConnection([
// replace "mysql" with correct driver needed for your environment
'driver' => 'mysql',
'host' => 'your_db_hostname',
'database' => 'your_db',
'username' => 'your_db_username',
'password' => 'your_db_password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]);
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->setAsGlobal();

Step 4.
- Set up any custom table classes you would like. For example:

class _users extends Illuminate\Database\Eloquent\Model {
protected $table = 'users';
}

Step 5.
- Put it to work

$user = _users::where('id',1)->first();
$users = _users::where('inactive',0)->get();
// or if you would like to just run a query without using a class for each table:$users = db::table('users')->where('inactive',0)->get();

We hope this helps those who wish to use the awesome power of the query builder within their own non-laravel website.

For full documentation of the query builder:
http://laravel.com/docs/5.1/queries

Coming soon we will show you how to use the Validation feature outside of Laravel!

--

--