在Laravel上创建多级类别并填充到select选项中,可以通过以下步骤实现:
这样,就可以在Laravel上创建多级类别并填充到select选项中了。
以下是一个示例代码:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::dropIfExists('categories');
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name', 'parent_id'];
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
}
// web.php
Route::get('/categories', 'CategoryController@index');
// CategoryController.php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::whereNull('parent_id')->with('children')->get();
return view('categories.index', compact('categories'));
}
}
<!-- categories/index.blade.php -->
<form>
<div class="form-group">
<label for="category">Category:</label>
<select class="form-control" id="category" name="category">
<option value="">Select Category</option>
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@foreach($category->children as $child)
<option value="{{ $child->id }}">- {{ $child->name }}</option>
@endforeach
@endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
这样,就可以在Laravel上创建多级类别并填充到select选项中了。请注意,以上示例中的代码仅供参考,实际应用中可能需要根据具体需求进行适当的修改。
领取专属 10元无门槛券
手把手带您无忧上云