/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ public function store(Request $request) { $validator = \Validator::make($request->all(), ['word_id' => 'required|exists:words,id', 'translation_id' => 'required|exists:translations,id']); if ($validator->passes()) { $user = \Auth::user(); $word = Word::find($request->input('word_id')); if (!$user->exercises()->where('word_id', $word->id)->first()) { if ($translation = $word->translations()->find($request->input('translation_id'))) { $exercise = new Exercise(); $exercise->setNewStatus($user); $exercise->user()->associate($user); $exercise->word()->associate($word); $exercise->save(); $exercise->translations()->attach($translation); $response = response()->json(['id' => $exercise->getId()], 201); } else { $response = response()->json(['errors' => ['This translation hasn\'t found in the exercise word.']], 404); } } else { $response = response()->json(['errors' => ['You already have this word in your exercises.']], 400); } } else { $response = response()->json(['errors' => $validator->messages()->all()], 400); } return $response; }
public function createExercise() { $users = User::all(); $words = Word::all(); foreach (range(1, 5) as $i) { $user = $users->random(); $word = $words->random(); $translation = $word->translations->random(); $exercise = new Exercise(); $exercise->status = 'new'; $exercise->reading = 10; $exercise->memory = 10; $exercise->user()->associate($user); $exercise->word()->associate($word); $exercise->translation()->associate($translation); $exercise->save(); echo 'Exercise id: ' . $exercise->id . '<br>'; } }