Home > OS >  Summation method laravel
Summation method laravel

Time:10-28

I have two fields, views, which just counts views, and add_to_views, a number that we add to views.

I need to display the sum of these numbers in the blade. Of course, you can just do this and everything will work.

{{ $article->views   $article->add_to_views }} Views

But I want to make the summation function separately and output the already ready number

Here is what I am trying to do, in the Article model itself I create a method

public function getTotalViews() {
        return $this->views   $this->add_to_views;
    }

Further in the controller I call it

$article = Article::where('id')->first();
$article->getTotalViews();

And I bring to the blade

{{ $article->getTotalViews() }} Views

But I get the error

Call to a member function getTotalViews() on null

CodePudding user response:

You're missing the ID for the Article that you're trying to get so it is null. It should actually be something like:

$article = Article::where('id', 1)->first();

Or alternatively, you could do

$article = Article::find(1);

For a longer explanation on the find method: https://laravel.com/docs/8.x/eloquent#retrieving-single-models

  • Related