I'm new at Laravel. I cannot understand how to insert data into the foreign key. Thank you for any answer. There are my code fragments:
name="user_id" is the foreign key of the Users' table which is held in the Course's table so I want that by the firstname and lastname attributes of the Users' table the Courses table would get user's ID.
<div class="row d-flex justify-content-center">
<div class="col-md-4">
<div class="form-group">
<select class="form-control dropdown-menu-arrow" name="subject" required>
<option value="" selected disabled>Kurso vadovas</option>
@foreach ($users as $user)
<option name="user_id">{{$user->firstname}} {{$user->lastname}}</option>
@endforeach
</select>
</div>
</div>
Schema::create('courses', function (Blueprint $table) {
$table->string('course_title');
$table->string('subject');
$table->mediumText('comments');
$table->bigIncrements('course_id');
$table->mediumText('description');
$table->integer('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('firstname');
$table->string('lastname');
$table->string('usertype');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
请测试这个
<option name="{{$user->id}}">{{$user->firstname}} {{$user->lastname}}</option>
you can use like this:
<select class="form-control dropdown-menu-arrow" name="subject" required>
<option value="" selected disabled>Kurso vadovas</option>
@foreach ($users as $user)
<option value="{{$user->id}}">{{$user->firstname}} {{$user->lastname}}</option>
@endforeach
</select>
and then get user id from controller:
$user_id = $request->subject;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.