Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Laravel Model without Eloquent?

As I am not sure, is it possible to create models with DB Class instead of Eloquent? I want to stay away from ORM.

Thanks

like image 358
Volatil3 Avatar asked Jan 14 '14 10:01

Volatil3


People also ask

Can I use eloquent without Laravel?

If you want, you can use Eloquent without Laravel. Actually, Laravel is not a monolithic framework. It is made up of several, separate parts, which are combined together to build something greater. However, nothing prevents you from using only selected packages in another application.

Why we use eloquent in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Is Laravel eloquent ORM?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database.


2 Answers

Yes of course its possible. You dont need to extend any class to make a model class that encapsulates business logic and consists of methods calling the DB class.

Just create your model inside app/models/MyModel.php like this

class MyModel{

    public static function getMyData(){
         return DB::table('users')->select('column')->get();

    }
}

then you should be fine to call your new class statically:

$data = MyModel::getMyData();

If you wanted to extend the DB class you could, though more likely you would be looking to extend the Database/Builder class to extend functionality but this is a complex topic and I suspect you would have asked a very different question if this was what you were after.

As I final note, I wouldn't steer clear of Eloquent, it's the greatest thing about Laravel amongst a lot of other great things

like image 71
SwiftD Avatar answered Sep 24 '22 21:09

SwiftD


Just remove the "extends Eloquent" and build the queries using the DB class.

like image 45
m1kfb Avatar answered Sep 24 '22 21:09

m1kfb