class User extends Authenticatable
{
public function EatingManagements()
{
return $this->belongsToMany('App\Model\EatingManagement');
}
class EatingManagement extends Model
{
protected $table = 'eating_managements';
public function users()
{
return $this->belongsToMany('App\User');
}
public function timezones()
{
return $this->belongsToMany('App\Model\Timezone');
}
}
class Timezone extends Model
{
protected $table = 'timezones';
public function Eating()
{
return $this->belongsToMany('App\Model\EatingManagement');
}
}
リポジトリ
<?php
namespace App\Repository;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Model\EatingManagement;
use App\Model\Timezone;
use App\User;
class EatingManagementRepository
{
private $paramNames = ['date', 'item', 'protein', 'riqid', 'carbo', 'calorie'];
public function __construct()
{
}
public function add($param, $user, $timezone)
{
$model = new EatingManagement();
foreach($this->paramNames as $name)
{
$model->$name = $param[$name];
}
$model->save();
$time = Timezone::where('id', $timezone)->first();
$this->attachToUser($model, $user);
$this->attachToTimezone($model, $time);
}
public function attachToUser($model, $user)
{
$model->users()->attach($user);
}
public function detachToUser($model, $user)
{
$model->users()->detach($user);
}
public function attachToTimezone($model, $timezone)
{
$model->timezones()->attach($timezone);
}
public function detachToTimezone($model, $timezone)
{
$model->timezones()->detach($timezone);
}
public function getParam()
{
return $this->paramNames;
}
}
コントローラー
<?php
namespace App\Http\Controllers\Eating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Repository\EatingManagementRepository;
class ApiController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->eatingManagement = new EatingManagementRepository();
}
/**
* データを1件登録する
*/
public function add(Request $request)
{
$paramNames = $this->eatingManagement->getParam();
$param = [];
foreach($paramNames as $name) {
$param[$name] = $request->contents[$name];
}
$this->eatingManagement->add($param, Auth::user(), $request->contents['timezone']);
return response()->json();
}
}