2

I'm not sure how to increment an integer in the controller

This is the what I tried. I'm grabbing the code, adding one and then saving it. This generates the error: "Call to a member function save() on string"

I'm returning the count to see the results in the browser. Running $count = Count::find(1)->count in Tinker gives the correct amount.

public function update(Request $request, Count $count)
{
    $count = Count::find(1)->count;

    $addOne = $count + 1;

    $count->save();

    return ($count);
}

Could someone show me how this is not working and what I can do to fix this?

This is the migration:

 public function up()
  {
     Schema::create('counts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('count');
        $table->timestamps();
     });
 }

This is the Modal:

  <?php

  namespace App;

  use Illuminate\Database\Eloquent\Model;

  class Count extends Model
  {
      protected $fillable = [
        'count'
      ];
  }
1
  • why not simply use $count++? Commented May 4, 2019 at 5:41

3 Answers 3

5

The problem is you are storing the count property, not the object itself.

$count = Count::find(1);

$count->count += 1;

$count->save();

return ($count);

Should do the trick.

Some more defined naming might help as well. Had to do some mental gymnastics to wrap my head around what count I was counting.

Sign up to request clarification or add additional context in comments.

Comments

3

The accepted answer is good, but this could be achieved even easier with the helper method that Laravel provides.

so this code:

$count = Count::find(1);
$count->increment('count');

return $count;

will do the same.

2 Comments

how is this easier than the accepted answer ??
fewer lines :) more readable on what you are doing, you don't have to agree with my definition of easier though :)
1

You can do

  $count = Count::find(1);
  $count->count += 1;
  $count->save();
  return $count;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.