Exhibitioner
Exhibitioner

Reputation: 123

How can I perform MySQL queries using the Laravel framework?

So I recently looked into the Laravel framework as I've been wanting to do for several months and so far It looks great and has some really helpful stuff in it.

However I've been trying to actually use database queries so that I can make use of real data but when I've tried to I haven't had much success.

I've configured the \config\database.php MySQL section, then tried using DB:: and all I got was an error:

the DB class in controllers doesn't exist

I have been reading through all the documentation and found nothing

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use DB;

class SongsController extends Controller {

        public function getSongs(){
        $songs = DB::table('songs')->get();

                return $songs;

        }      

}

View:

<?php  
        foreach ($songs as $song){
    var_dump($song->song);
        }

My mysql in \config\database.php:

'mysql' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST', 'localhost'),
    'database'  => env('DB_DATABASE', 'songs'),
    'username'  => env('DB_USERNAME', 'root'),
    'password'  => env('DB_PASSWORD', 'password'),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
    'strict'    => false,
],

Upvotes: 1

Views: 328

Answers (2)

maztch
maztch

Reputation: 1697

In your mysql config:

'database'  => env('DB_DATABASE', 'songs'),

It says: look if enviroment variable is set, if it exists in your .env file (in your root), use it, if not, use default "songs".

http://laravel.com/docs/5.0/configuration#environment-configuration

Upvotes: 1

maztch
maztch

Reputation: 1697

You need to add use DB; in the top of your file. Remember Laravel5 uses namespaces.

<?php namespace App\Http\Controllers;
use DB;

Upvotes: 0

Related Questions