M
M
Mors Clamor2020-11-20 03:07:10
Laravel
Mors Clamor, 2020-11-20 03:07:10

How to use Eloquent apart from laravel?

Hello! I have a self-written project in which I decided to use Eloquent as ORM. However, I was not able to take advantage of all its features: Query Builder functions do not work in the context of models. That is, the code will return null, while returning the desired result. However, I do not intend to interfere with the work with the database in the controller. I decided to create a model class child from Eloquent Model
\models\User::where('test', '=', 123);
DB::table('users')->where('test', '=', 123);

namespace core;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Capsule\Manager as DB;

abstract class Model extends EloquentModel
{
    public function findWhere($param1, $param2, $param3) {
        
            return DB::table($this->table)->where($param1, $param2, $param3)->get();
    }
}


But then, because of $this->table, there is a binding to the object context, and this is somehow crooked. Is there some way to solve the problem nicely?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2020-11-20
@66demon666

Everything works great. We connect the illuminate/database package We extend
our models from eloquent/model and that's it.
Don't forget to specify protected $table = 'my-table'; if the table does not match the eloquent naming convention

F
feycot, 2020-11-23
@feycot

Have a look at the https://github.com/hexlet-components/php-eloquent-blog repository for how to work with models outside of Laravel. In principle, all this should work out of the box.
You are inheriting from the Eloquent model. but still use it as a query builder. Configure your class and specify the table (for example, in a constructor or explicitly in a property). Looks like you're using inheritance incorrectly)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question