猿问

使用Laravel在控制器中递增整数

我不确定如何在控制器中增加整数


这就是我尝试过的。我正在抓取代码,添加一个然后保存。这将产生错误:“在字符串上调用成员函数save()”


我将返回计数以在浏览器中查看结果。在Tinker中运行$ count = Count :: find(1)-> count可以得出正确的金额。


public function update(Request $request, Count $count)

{

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


    $addOne = $count + 1;


    $count->save();


    return ($count);

}

有人可以告诉我这是怎么不起作用的,我该怎么做才能解决?


这是迁移:


 public function up()

  {

     Schema::create('counts', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->integer('count');

        $table->timestamps();

     });

 }

这是模态:


  <?php


  namespace App;


  use Illuminate\Database\Eloquent\Model;


  class Count extends Model

  {

      protected $fillable = [

        'count'

      ];

  }


12345678_0001
浏览 176回答 3
3回答

慕斯709654

问题是您存储的是count属性,而不是对象本身。$count = Count::find(1);$count->count += 1;$count->save();return ($count);应该做的把戏。一些更定义的命名也可能会有所帮助。不得不做一些精神体操来把我的头缠在我所数的数上。

哔哔one

可接受的答案是好的,但是使用Laravel提供的帮助程序方法甚至可以更轻松地实现。所以这段代码:$count = Count::find(1);$count->increment('count');return $count;将做同样的事情。

ITMISS

你可以做&nbsp; $count = Count::find(1);&nbsp; $count->count += 1;&nbsp; $count->save();&nbsp; return $count;
随时随地看视频慕课网APP
我要回答