#解決したいこと
if文を用いて、データが存在しない場合にsaveメソッドを用いてデータを保存したい。
#試したこと
下機の記述を追加
php
1 2 3 4 5public function send() 6 { 7 $today = date("Y-m-d"); 8 $date = \App\StandingUpRecord::where('user_id',Auth::id())->where('created_at', $today)->get(); 9 if ($date === null){ 10 11 12 $record = new StandingUpRecord(); 13 14 $record->number_of_times = 10; 15 16 $record->user_id = Auth::id(); 17 18 $record->save(); 19 }else{ 20 $date2 = \App\StandingUpRecord::where('user_id',Auth::id())->where('created_at', $today)->increment('number_of_times', 10); 21 22 } 23 return view('standing-up-record.rest'); 24 25 }
試した結果
#コード
app/Http/Controllers/StandingUpRecords.php
php
1 2 3 4 5 6 7<?php 8 9namespace App\Http\Controllers; 10 11use Illuminate\Http\Request; 12use App\StandingUpRecord; 13use Illuminate\Support\Facades\Auth; 14 15class StandingUpRecords extends Controller 16{ 17 public function index() 18 { 19 return view ('standing-up-record.index'); 20 } 21 22 public function new() 23 { 24 return view ('standing-up-record.new'); 25 } 26 27 public function rest() 28 { 29 return view ('standing-up-record.rest'); 30 } 31 32 public function send() 33 { 34 $today = date("Y-m-d"); 35 $date = \App\StandingUpRecord::where('user_id',Auth::id())->where('created_at', $today)->get(); 36 if ($date === null){ 37 38 39 $record = new StandingUpRecord(); 40 41 $record->number_of_times = 10; 42 43 $record->user_id = Auth::id(); 44 45 $record->save(); 46 }else{ 47 $date2 = \App\StandingUpRecord::where('user_id',Auth::id())->where('created_at', $today)->increment('number_of_times', 10); 48 49 } 50 return view('standing-up-record.rest'); 51 52 } 53 54} 55 56
app/StandingUpRecord.php
php
1 2 3 4<?php 5 6namespace App; 7 8use Illuminate\Database\Eloquent\Model; 9 10class StandingUpRecord extends Model 11{ 12 protected $fillable = ['number_of_times', 'user_id']; 13 protected $table = 'standing_up_records'; 14 15 public function user() 16{ 17 return $this->belongsTo('App\User'); 18} 19} 20
views/standing-up-record/new.blade.php
php
1 2 3 4 5<form action="send" method="post"> 6@csrf 7<input type="submit" value="10回立ち座りした"> 8</form> 9 10
views/standing-up-record/rest.blade.php
php
1 2 3 4 5 6 7休憩中です 8 9<div class="links"> 10 <a href="new">もう10回頑張る</a> 11 </div> 12 13 <div class="links"> 14 <a href="/standing-up-record">今日は終わりにする</a> 15 </div> 16
よろしくお願いします。