I'm trying to use Eloquent ORM from Laravel in my own legacy project. I have the models set-up and Eloquent is working fine but I can't understand how to run a raw SQL query using the eloquent database connection inside the model. I need to run raw SQL queries for now until I can refactor the entire code base over to use the ORM.
namespace App\Providers;
use Illuminate\Database\Capsule\Manager;
use League\Container\ServiceProvider\AbstractServiceProvider;
class DatabaseServiceProvider extends AbstractServiceProvider
{
protected $provides = [
Manager::class
];
public function register()
{
$container = $this->getContainer();
$config = $container->get('config');
$config = $config->get('db.mysql');
$capsule = new Manager;
$capsule->addConnection([
$config
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$container->share(Manager::class, function () use ($capsule){
return $capsule;
});
}
}
Now in my model I have the following:
namespace App\Models;
use Illuminate\Database\Eloquent\Model as Eloquent;
class User extends Eloquent
{
protected $table = '_users';
}
Then I'm trying to call that model in my controller:
namespace App\Controllers;
use App\Views\View;
use App\Models\User;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class HomeController
{
protected $view;
public function __construct(View $view)
{
$this->view = $view;
}
public function index(RequestInterface $request, ResponseInterface $response)
{
$user = User::find(1);
dump($user);
}
}
So this all works nicely but I can't figure out how to run a raw query inside of the model? Obviously the below won't work but I want something like that, creating a new function and it returns the result:
Model:
public function customQuery()
{
$query = 'SELECT * FROM _users';
return $query;
}
Controller:
$user = new User;
$user->customQuery();