Daniel Morgan
Daniel Morgan

Reputation: 561

Using models in laravel 4

Just really what the title says, does anybody have a decent explanation on how to use models properly in laravel 4? I'm fine with using the pre-existing User model. But I read somewhere that queries and such should be done in a model of your own.

So what I have is basically a form where you can make a status update (like facebook) and it stores it in a database but the query is run through the controller.

I want it to be done through a model.

Any information on this would be great! Thanks in advance

Upvotes: 2

Views: 3243

Answers (1)

The Alpha
The Alpha

Reputation: 146269

It's a broad question and right place to learn about how to use model in Laravel-4 is the laravel site itself, but anyways.

Actually, model is the the place where you should keep the business logic in any MVC framework, it could be database related or anything else that is the heart of the application and controller and View are just two parts of the application whose responsibility is only communicate to the model, fetch data and present it to the user but all the data processing should be done in the model and controller should be kept slim and view is only a mechanism to present the user a UI.

So, if you want to have a User model in your application (laravel-4) then you may extend it from Eloquent like

class User extends Eloquent{
    // code goes here
}

and then call it's methods from the controller, like

$user = User::get(1);

then passing it to the view like

return View::make('viewname', $user);

That's it. But, if you think, where the find method come from then, it's because, you have extended the Eloquent model and in that model all the necessary methods (find e.t.c) are available and your User model inherited the behavior of Eloquent model, so you can use all the methods from User and it's not necessary to a single method in your User model unless you need to write some special methods for that User model, like relationship functions and so. well, the perfect place to seek help or to know the basic about it is the Laravel site, try to understand it from there and if you fail or just stuck anywhere then come here to ask with specific problem. Also, check Basic Database Usage and Query Builder.

BTW, you may check this post for a detailed answer on model of MVC.

Upvotes: 9

Related Questions