i want to ask you how to select FOREIGN KEY (from “doa_id in “doas” table) when user create a new data (to the “notes table) in a form. This is my code :
NoteController.php
public function create() { return view('note/create'); } public function store(Request $request) { $userId = Auth::user()->id; Note::create([ 'title' => $request->title, 'detail' => $request->detail, 'user_id' => $userId, 'mood_id' => $request->mood_id, 'doa_id' => $request->doa_id, ]); return redirect('notes'); }
2021_05_28_020438_create_notes_table.php migration
class CreateNotesTable extends Migration { public function up() { Schema::create('notes', function (Blueprint $table) { $table->id('note_id'); $table->string('title'); $table->date('created_at'); $table->date('updated_at'); $table->text('detail'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users'); //mood FK $table->unsignedBigInteger('mood_id'); $table->foreign('mood_id')->references('mood_id')->on('moods'); //doa FK $table->unsignedBigInteger('doa_id'); $table->foreign('doa_id')->references('doa_id')->on('doas'); }); } public function down() { Schema::dropIfExists('notes'); } }
and this is my dropdown html :
<div class="container"> <label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label> <select class="form-select" style="color: #41A7A5" aria-label="Default select example"> <option selected>Pilih doa</option> </select> </div>
In Dropdown option, I want to show “doa_name” based on it’s “doa_id”
Thank you 🙂
Advertisement
Answer
You can put the logic in the NoteController and the view. For example, to get a collection of all options for the foreign key, pass the collection to the view.
public function create() { $doas = Doas::all(); return view('note/create', compact('doas')); }
Then on the view, you can perform a foreach
loop using the select
HTML tag.
<div class="container"> <label class="form-label text-white" style="font-weight: bold;" for="doa">Doa terkait</label> <select class="form-select" style="color: #41A7A5" aria-label="Default select example"> @foreach ($doas as $doa) <option value="{{$doa-id>}}">{{$doa->name}}</option> @endforeach </select> </div>
After this, it’s just using the input in your store()
method.