如何在编辑我的数据库时选中复选框

How to have the checkbox checked when editing my database

我有一个枢轴 table themes_article,当我创建 article 时,它在枢轴 table.

内运行良好

我现在想做的是,当我编辑一篇文章时,我已经选中的复选框需要被选中。

这是我的代码:

@foreach ($themes as $theme)  
  <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="themeCheckbox[{{$theme->theme_id}}]" value="1" {{ $article->themeCheckbox[{{$theme->theme_id}}] || old('themeCheckbox[{{$theme->theme_id}}]', 0) === 1 ? 'checked' }} >
      <label class="form-check-label">{{ $theme->nom_theme }}</label>
  </div>
@endforeach

我正在使用它来将我的数据插入我的数据透视表 table(它运行良好):

  $themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
  $article->save();
  $article->theme()->attach($themes);

我的函数将更新我的数据:

public function editer_article(Request $request, $idArticle)
{
    $data = $request->validate([ // $data = $this->validate($request
        'titreArticle' => 'bail|required|between:5,40',
        'typeArticle' => 'bail|required',
        'themeCheckbox' => 'required',
        'themeCheckbox.*' => 'required',
        'contenuArticle' => 'bail|required'
        
    ]);
    $type_articles = Type_article::findOrFail($data['typeArticle']);
    $article = Article::where('id_article',$idArticle)->firstOrFail();
    $article->type_article()->associate($type_articles);
    $themes = Theme::whereIn('theme_id', array_keys($data['themeCheckbox']))->get();
    $article->titre = $data['titreArticle'];
    $article->contenu = $data['contenuArticle'];

    $article->save();
    $article->theme()->sync($themes);

    return view('admin/article/admin_validation_edition');
}

我遇到了这个错误:

 syntax error, unexpected '{', expecting ']' (View:

我想我没有很好地使用输入中的条件...

亲切

确保你没有打错字。导致其难以追踪。我不知道你的控制器在哪里,那是什么控制器?创建或其他东西。您可以分享更多详细信息...

正如@Unflux 所正确概述的那样,以下代码段中的嵌套花括号不是必需的:

<input
   class="form-check-input"
   type="checkbox"
   name="themeCheckbox[{{$theme->theme_id}}]"
   value="1"
   {{ $article->themeCheckbox[$theme->theme_id] || old('themeCheckbox[$theme->theme_id]', 0) === 1 ? 'checked' }} >
<label for="gender">Gender: </label>
<div class="custom-control custom-radio custom-control-inline">
    <input class="custom-control-input" id="male" name="gender"
        type="radio" value="Male"
        {{ $dealer->gender == 'Male' ? 'checked' : '' }} />
    <label class="custom-control-label" for="male">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
    <input class="custom-control-input" type="radio" id="female"
        name="gender" value="Female"
        {{ $dealer->gender == 'Female' ? 'checked' : '' }} />
    <label class="custom-control-label" for="female">Female</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
    <input class="custom-control-input" type="radio" id="na"
        name="gender" value="NotApplicable"
        {{ $dealer->gender == 'NotApplicable' ? 'checked' : '' }} />
    <label class="custom-control-label" for="na">N/A</label>
</div>


这是一个简单的例子,说明如何实现这一点。

假设您的 ArticleTheme 对象有模型和 table,它们都至少有一个 name 字段。 Laravel 中命名枢轴 tables 的惯例是按字母顺序组合单数模型名称。所以为此它将是 article_theme。这个 table 至少应该有 article_idtheme_id.

的字段

database/migrations/create_article_theme_table.php

Schema::create('article_theme', function (Blueprint $table) {
    $table->id();
    $table->foreignId('article_id')->constrained();
    $table->foreignId('theme_id')->constrained();
    $table->timestamps();
});

Article 模型中定义它与 Theme 的关系。我还添加了一个方便的方法来检查 Theme 是否关联到视图中使用的 Article

app/Models/Article.php

class Article extends Model
{
    use HasFactory;

    public function themes()
    {
        return $this->belongsToMany(Theme::class);
    }

    /**
     * convenience function for checking if a theme is associated to the article
     */
    public function scopeHasTheme(\Illuminate\Database\Eloquent\Builder $builder, Theme $theme)
    {
        return $this->themes()->where('theme_id', $theme->id)->exists();
    }
}

如果您愿意,您可以为 Theme 模型执行逆运算。

app/Models/Theme.php

class Theme extends Model
{
    use HasFactory;

    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }
}

定义一些路由来显示您的 Article 表单和另一个来处理它。

routes/web.php

// define a route to show the form for editing an existing Article
Route::get('/articles/{article}', [\App\Http\Controllers\ArticleController::class, 'show'])
    ->name('articles.show');

// define a route to process the update Article form submission
Route::put('/articles/{article}', [\App\Http\Controllers\ArticleController::class, 'update'])
    ->name('articles.update');

ArticleController

上构建函数

app/Http/Controllers/ArticleController.php

class ArticleController extends Controller
{
    // process the form submission
    public function update(Request $request, Article  $article)
    {
        $article->themes()->sync($request->themes);

        return redirect(route('articles.show', $article));
    }

    // display the form passing through the article and all themes
    public function show(Article $article)
    {
        return view('articles.show', [
            'article' => $article,
            'themes' => Theme::all()
        ]);
    }
}

视图是 'magic' 发生的地方。我们在 Article 模型上使用 hasTheme 函数来检查给定的 Theme 是否与 Article 相关联,如果是,则将 checked 属性添加到checkbox.

resources/views/articles/show.blade.php

<form action="{{ route('articles.update', $article) }}" method="POST">
    @csrf
    @method("PUT")

    <h4>{{ $article->name }}</h4>

    @foreach ($themes as $theme)
        <div>
            <input type="checkbox" name="themes[]" value="{{ $theme->id }}"  
                 id="theme-{{ $theme->id }}" @if($article->hasTheme($theme)) checked @endif>
            <label for="theme-{{ $theme->id }}">{{ $theme->name }}</label>
        </div>
    @endforeach

    <button type="submit">Save</button>
</form>

<hr>

<!-- Output the name of all themes associated to the article for reference -->
<h4>Attached Themes</h4>
@foreach ($article->themes as $theme)
    <div>
        {{ $theme->name }}
    </div>
@endforeach

假设您的数据库中有一些 articlesthemes,例如,如果您转到 /articles/1,您应该会看到您的文章以及每个 checkbox theme 在您的数据库中以及与您的 article checked.

关联的数据库中