/** * 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(), ['body' => 'required', 'translation_id' => 'sometimes|exists:translations,id', 'via_dictionary' => 'sometimes|boolean']); if ($validator->passes()) { if ($request->input('via_dictionary')) { $definitions = \YaDictionary::lookup($request->input('body')); if ($definitions) { foreach ($definitions as $definition) { $partOfSpeech = $definition->getPartOfSpeech(); if (!($position = Position::where('body', $partOfSpeech)->first())) { $position = Position::create(['body' => $partOfSpeech]); } if (!Word::where('body', $definition->getText())->where('position_id', $position->id)->first()) { $word = new Word(); $word->body = $definition->getText(); $word->ts = $definition->getTranscription(); $word->position()->associate($position); $word->save(); $translationIds = []; foreach ($definition->getTranslations() as $yaTranslation) { if (!($translation = Translation::where('body', $yaTranslation->getText())->first())) { $translation = Translation::create(['body' => $yaTranslation->getText()]); } $translationIds[] = $translation->id; } $word->translations()->attach($translationIds); } } $response = response('This word has created from the dictionary', 201); } else { $response = response()->json(['errors' => ['This word has not found in the dictionary.']], 404); } } else { if ($translationId = $request->input('translation_id')) { $word = Word::create(['body' => $request->input('body')]); $word->translations()->attach($translationId); $response = response()->json(['id' => $word->getId()], 201); } else { $response = response()->json(['errors' => ['It needs a translation.']], 400); } } } else { $response = response()->json(['errors' => $validator->messages()->all()], 400); } return $response; }
public function yandexDictionary() { $result = \YaDictionary::lookup('abc'); foreach ($result as $dkey => $definition) { $response[$dkey]['ts'] = $definition->getTranscription(); $response[$dkey]['position'] = $definition->getPartOfSpeech(); $response[$dkey]['body'] = $definition->getText(); foreach ($definition->getTranslations() as $tkey => $translation) { $response[$dkey]['translations'][$tkey] = $translation->getText(); } } dd([$result, $response]); }