Поэтому, когда я хочу создать новый торт, мне нужно, чтобы названия категорий отображались в раскрывающемся списке. Я установил отношения hasMany
между Category.php
и Cake.php
.
В настоящее время я могу получить только category_id
в значении параметра, но не название категории.
Category.php : Где яобъявленные отношения.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = [];
public function cake()
{
return $this->hasMany(Cake::class, 'category_id', 'id');
}
}
CreateCakesTable.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCakesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cakes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->decimal('price');
$table->integer('size');
$table->boolean('published')->default(false);
$table->unsignedInteger('category_id');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('cakes');
}
}
CreateCategoriesTable.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
create.blade.php
<div class="form-group">
<label for="category_id" @error('category_id') class="text-danger" @enderror>Categorie</label>
<select class="form-control @error('category_id') is-invalid @enderror" name="category_id" id="category_id">
<option disabled selected value> -- Selecteer een categorie -- </option>
@foreach ($cake as $cake)
<option value="{{ $cake->category->id ?? '' }}">{{ $cake->category->name ?? 'Geen categorie'}}</option>
@endforeach
</select>
@error('category_id')
<span class="invalid-feedback d-block" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>