0

Currently I have this code:

$image = Image::find($id);
$views = $image->views;
$image->views = $views + 1;
$image->save();

The code is located in the function which returns the view for a specificImage. The point is that whenever a user requests this view, the image views count should increase, however, I don't like having this logic in the function that returns the view so I am hoping to create a:

public function updateImageViews() {
    logic that updates views;
}

somewhere in my controllers (I've been thinking about putting it in my ArtworkController) and then just call the function in my function that returns the view.

Now I'm wondering whether this is a good way to do it. The problem is that I don't think this will work as of now since I don't think I'm allowed to call a function from another controller without doing something first.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • What difference does it make in the end, whether it’s a function containing the code or just the code itself doing the necessary stuff? – Daniel Protopopov Oct 17 '18 at 18:01

1 Answers1

1

For more complicated things, you use services. You put in there business logic or complex operations. Then you can call this service in other services or multiple controllers - whatever you need.

About above code, well it could be really refactored into single line, so there might be no need to extract it to other method. Simplified code for this looks like this:

Image::find($id)->increment('views');

However in case you would really like to extract the code somewhere, I would use for such simple code just model (in this case Image) with static method:

public static function updateViews($id)
{
    $image = static::find($id);
    $views = $image->views;
    $image->views = $views + 1;
    $image->save();

    return $image;
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Oh wow, didn't know I could increment it using so little code. Anyway, if I were to need a simple function which is not exactly suitable to put in any model, where should I place it? Obviously I could put that updateViews() function in the Image model since it makes sense, but if the function were something like changeFtoC() I wouldn't be able to put it in any model since there won't be any relation. – Onyx Oct 17 '18 at 18:13
  • @Bobimaru If you need just functions, take a look at https://stackoverflow.com/questions/43168719/custom-helper-classes-in-laravel-5-4/43169120#43169120 - I've explained in there how can it be done – Marcin Nabiałek Oct 17 '18 at 18:31
  • `Image::whereId($id)->increment('views')` should do the same thing, but without first running a select statement – Travis Britz Oct 17 '18 at 19:09
  • 1
    @TravisBritz That's true, but depending on app, it might be better to get actual model to trigger any additional actions (observers for example) – Marcin Nabiałek Oct 17 '18 at 19:23