|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Http\Controllers; |
| 4 | + |
| 5 | +use App\Models\{Word, Category, CategoryWord}; |
| 6 | +use Illuminate\Http\Request; |
| 7 | + |
| 8 | +class CategoryWordController extends Controller |
| 9 | +{ |
| 10 | + protected $word; |
| 11 | + protected $category; |
| 12 | + |
| 13 | + // Show the form for creating a new CategoryWord instance |
| 14 | + public function showCreate(Request $request) |
| 15 | + { |
| 16 | + $wordId = $request->query('word'); |
| 17 | + $categoryId = $request->query('category'); |
| 18 | + $returnTo = $request->query('returnTo'); |
| 19 | + |
| 20 | + $word = Word::findOrFail($wordId); |
| 21 | + $category = Category::findOrFail($categoryId); |
| 22 | + return view('categoryword.create', [ |
| 23 | + 'word' => $word, |
| 24 | + 'category' => $category, |
| 25 | + 'returnTo' => $returnTo, |
| 26 | + ]); |
| 27 | + } |
| 28 | + |
| 29 | + // Store the new CategoryWord instance |
| 30 | + public function store(Request $request) |
| 31 | + { |
| 32 | + $validated = $request->validate([ |
| 33 | + 'word_id' => 'required|exists:words,id', |
| 34 | + 'category_id' => 'required|exists:categories,id', |
| 35 | + 'difficulty_override' => 'nullable|numeric', |
| 36 | + 'example_sentence' => 'nullable|string', |
| 37 | + ]); |
| 38 | + |
| 39 | + // Create a new CategoryWord instance |
| 40 | + CategoryWord::create($validated); |
| 41 | + |
| 42 | + // return to either the edit word page, or edit category page depending on where we came from |
| 43 | + $returnTo = $request->input('return_to'); |
| 44 | + if ($returnTo === 'word') { |
| 45 | + return redirect()->route('showEditWord', $validated['word_id'])->with('success', 'successfully added to that category!'); |
| 46 | + } else { |
| 47 | + return redirect()->route('showEditCategory', $validated['category_id'])->with('success', 'word added successfully!'); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments