Reputation: 661
I've created a model called Hangman. Inside a controller I'm inserting a row in the database like this
$hangman = new Hangman();
$hangman->word = 'exampleWord';
$hangman->lives = 3;
$hangman->save();
So far so good.
I've got two questions:
1) Is it best practice to keep inserting things in the controller?
I assume NO, so I created this method in the model, which I think would be cleaner to call from the controller
public function insert($word, $lives)
{
$hangman = new Hangman();
$hangman->word = $word;
$hangman->lives = $lives;
$hangman->save();
return $hangman;
}
So, my real question (assuming question 1 is NO) is:
2) How would I call this method from the controller?
This doesn't work
\App\Hangman::insert('exampleword', 4);
Namespaces are correct.
I know it's very basic, thanks guys
Upvotes: 2
Views: 2676
Reputation: 25384
Nobody can answer your first question properly, as it's a matter of personal preference and people have various opinions. Putting it in the model may be a good idea, as might putting it in a repository. In the right application, having it in a controller might be worth it, whereas other systems may favour yet other solutions.
As for your second question: since you're in the Hangman model, you should make the self-referential call static, and also the method itself.
public static function insert($word, $lives)
{
$hangman = new static;
$hangman->word = $word;
$hangman->lives = $lives;
$hangman->save();
return $hangman;
}
And that should be enough. You could also save yourself a few lines:
public static function insert($word, $lives)
{
return static::create(compact('word', 'lives'));
}
Upvotes: 3
Reputation: 3875
You can't call a method with :: double colons unless the method is static. Therefore you should change your method to a static method.
public static function insert($word, $lives)
{
// logic
}
You are actually doing this the wrong way. The insert method has to be in the Controller, not inside the model. Move your insert method to Controller and use it. Creating an instance of the Model inside the Controller is the right way to do it.
Right now, you are trying to create an instance of a class inside the same class (Hangman inside Hangman). That's not the right way to do it in MVC architecture.
Upvotes: 1