Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Class 'DB' not found

Tags:

laravel-5

I have ChatController located in app/http/controllers like so:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use DB;

class ChatController extends Controller implements MessageComponentInterface {

    protected $clients;

    function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) 
    {
        $this->clients->attach($conn);
    }

    public function onMessage(ConnectionInterface $conn, $msg) 
    {
        foreach ($this->clients as $client) 
        {
            if ($client !== $conn )
                $client->send($msg); 

            DB::table('messages')->insert(
                ['message' => $msg]
            );
        }
    }

    public function onClose(ConnectionInterface $conn) 
    {
        $this->clients->detach($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e) 
    {
        echo 'the following error occured: ' . $e->getMessage();
        $conn->close();
    }

}

And I have chatserver.php file in the root like so:

<?php
require  'vendor/autoload.php';

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();

If I remove

DB::table('messages')->insert(
                    ['message' => $msg]
                );

from the ChatController and start chatserver.php it works, but if I don't remove it then the server starts but as soon as I send a message I get this error:

Fatal error: Uncaught Error: Class 'DB' not found in C:\wamp\www\laraveltesting\app\Http\Controllers\ChatController.php:31

Why won't it use DB? I am extending the laravel controller.

like image 753
user6562256 Avatar asked Jul 30 '16 11:07

user6562256


4 Answers

This one is better

use Illuminate\Support\Facades\DB;

Or you can use a slash('/') before DB like below

/DB::table('messages')->insert(
                ['message' => $msg]
            );
like image 85
Sibasankar Bhoi Avatar answered Nov 06 '22 22:11

Sibasankar Bhoi


As previously advised First use

use Illuminate\Support\Facades\DB;

then go /bootstrap/app.php and uncomment

$app->withFacades();
like image 2
Ndeto Avatar answered Nov 06 '22 21:11

Ndeto


try using this

use Illuminate\Support\Facades\DB;

instead of

use DB;
like image 1
jonju Avatar answered Nov 06 '22 22:11

jonju


for Laravel 5 and up simply just use this

use DB;

instead of

use Illuminate\Support\Facades\DB;

which is use for Laravel 4 version

like image 1
Miguellito Avatar answered Nov 06 '22 21:11

Miguellito