scott
scott

Reputation: 3202

how to run method in model instead of controller in laravel 5.1?

I have following method in my controller:

public function store()
{
    $data=Input::all();
    User::create($data);
}

The above code works perfectly. My question is can we run the above method in model without writing in controller? And which is the best approach?

Upvotes: 1

Views: 609

Answers (3)

djt
djt

Reputation: 7535

In this circumstance, I don't think you gain much from moving things arounds.

If this is your Controller method:

public function store()
{
    $data=Input::all();
    User::create($data);
}

then this makes sense. The input data is being handled by the controller method, and is being passed to the create method on your User Model.

If however, there was more logic required before creating a User record, then it'd be perfectly valid to abstract that logic to your User model. But as it stands though, I think your current implementation is appropriate.

Upvotes: 1

user4294557
user4294557

Reputation:

you can try following way

in your model

public function insetUser()
{
        $input = Input::all();
        User::create($input);
    //here instead of User,you can use self like  self::create($input);
}

in controller you can

public function store()
{
    User::insetUser();
}

Upvotes: 3

violator667
violator667

Reputation: 499

If it is in model, how you are going to trigger it?

It is in fact only one line of code

User::create(Input::all());

What it is here is the instance of model User and method create with injected model Input. Of couse you may set (model) User.php:

public function storedata()
{
 return $this->create(Input::all());
}

And then run it in your controller:

User::storedata();

But is it better? ;-)

Upvotes: 2

Related Questions