Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gervis_Andjoua's avatar

I want to display title with price .

@foreach($ingredients as $ingredientId => $ingredientTitle) <input class="form-check-input" type="checkbox" id="ingredient_id" value="{{ $ingredientId }}" name="ingredients[]" {{ array($ingredientId, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}> {{ $ingredientTitle }}

0 likes
46 replies
vincent15000's avatar

More readable now no ?

@foreach($ingredients as $ingredientId => $ingredientTitle)
	<input
		class="form-check-input"
		type="checkbox"
		id="ingredient_id"
		value="{{ $ingredientId }}"
		name="ingredients[]" {{ array($ingredientId, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}
	> {{ $ingredientTitle }}
@endforeach

When you write @foreach($ingredients as $ingredientId => $ingredientTitle), be careful, what you are naming $ingredientId isn't the ingredient id, but only the index of the item in the loop.

1 like
gych's avatar

From what I see in your code the $ingredients only contain the $ingedrientTitle So you'll have to add the price in your controller and then use something like this

@foreach($ingredients as $index => $ingredient)
	<input
		class="form-check-input"
		type="checkbox"
		id="ingredient_id"
		value="{{ $index }}"
		name="ingredients[]" {{ array($index , old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}
	> 
{{ $ingredient->title }} {{ $ingredient->price}}

Keep in mind that example above won't work if you don't change anything in your controller method.

Also like @vincent15000 already metioned, its not good to name the index of your loop $ingredientId. Name it $index or $key like I've done in the example.

1 like
Gervis_Andjoua's avatar

@gych i've add price in my controller now

public function edit(string $id) { // Récupérer l'alimentaire à éditer depuis la base de données $alimentaire = Alimentaire::findOrFail($id);

    // Récupérer toutes les catégories, les ingrédients, les tailles et les suppléments depuis la base de données
    $categories = Category::all();
    $ingredients = Ingredient::pluck('title','id','price');
    
    $sizes = Size::all();
    $supplements = Supplement::all();

    // Passer les données récupérées et l'alimentaire à éditer à la vue correspondante
    return view('alimentaires.edit', compact('alimentaire', 'categories', 'ingredients', 'sizes', 'supplements'));
}
Gervis_Andjoua's avatar

After to have modifying the controller and views . I've this error : Attempt to read property "title" on string below my code

views edit @foreach($ingredients as $index => $ingredient) <input class="form-check-input" type="checkbox" id="ingredient_id" value="{{ $index }}" name="ingredients[]" {{ array($index, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}> {{ $ingredient->title }} {{$ingredient->price}}

gych's avatar

I see but use select instead of pluck because pluck is used to pluck a single column from a collection. Select works with multiple columns.

$ingredients = Ingredient::select('id', 'title', 'price')->get();

Try now with this code, it should display title + price I also changed array to in_array to check if it needs to be checked or not and added index to input id.

@foreach($ingredients as $index => $ingredient)
    <input
        class="form-check-input"
        type="checkbox"
        id="ingredient_{{ $index }}"
        value="{{ $index }}"
        name="ingredients[]" {{ in_array($index, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}
    > 
    {{ $ingredient->title }} {{ $ingredient->price}}
gych's avatar

Which data exactly doesn't change, the title and price after you update it or the checked value ?

gych's avatar

Try to update the code to this

@foreach($ingredients as $index => $ingredient)
    <input
        class="form-check-input"
        type="checkbox"
        id="ingredient_id"
        value="{{ $index }}"
        name="ingredients[]" {{ in_array($index, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}
    > 
    {{ $ingredient->title }} {{ $ingredient->price}}
1 like
gych's avatar

Can you share the code of the controller method where you save the data?

Gervis_Andjoua's avatar

@gych

this is my controller method store public function store(Request $request) { // dd($request->all());

    // $request->validate([
    //     // 'categories_id' => 'required|exists:categories,id',
    //     'categories_id' => 'required',
    //     'title' => 'required|string|max:255',
    //     'cover' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
    //     'description' => 'required|string',
    //     'ingredients_id' => 'nullable',
    //     'size_id' => 'nullable',
    //     'supplement_id' => 'nullable'
    // ]);

    $alimentaire = new Alimentaire();
    $alimentaire->categorie_id = $request->categorie_id;
    $alimentaire->title = $request->title;
    //Enregistrement de l'image 
    if ($request->hasFile('cover')) {
        $alimentaire->cover = $request->file('cover')->store('images/posts');
    }
    $alimentaire->description = $request->description;
    $alimentaire->save();
    if ($request->ingredients) {
        foreach ($request->ingredients as $k => $item) {
            $alimentaire->ingredient()->attach(
                [
                    'alimentaire_id' => $alimentaire->id,
                    'ingredient_id' => $item
                ]
            );
        }
    }
    if ($request->sizes) {
        foreach ($request->sizes as $k => $item) {
            $alimentaire->size()->attach(
                [
                    'alimentaire_id' => $alimentaire->id,
                    'size_id' => $item
                ]
            );
        }
    }
    if ($request->supplements) {
        foreach ($request->supplements as $k => $item) {
            $alimentaire->supplement()->attach(
                [
                    'alimentaire_id' => $alimentaire->id,
                    'supplement_id' => $item
                ]
            );
        }
    }
    

    $alimentaire->save();

    return redirect()->route('alimentaires.index')->with('success', 'Aliment créé avec succès');
}
Gervis_Andjoua's avatar

Also.

This is controller methode Update public function update(Request $request, string $id) { $alimentaire = Alimentaire::find($id); $alimentaire->categorie_id = $request->categorie_id; $alimentaire->title = $request->title; //Enregistrement de l'image if ($request->hasFile('cover')) { $alimentaire->cover = $request->file('cover')->store('images/posts'); } $alimentaire->description = $request->description;

    $alimentaire->save();
    
    $alimentaire->ingredient()->sync($request->ingredients);

    // Mettre à jour les relations avec les tailles
    $alimentaire->size()->sync($request->sizes);

    // Mettre à jour les relations avec les suppléments
    $alimentaire->supplement()->sync($request->supplements);

    return redirect()->route('alimentaires.index')->with('success', 'Aliment modifié avec succès');
}

/**
 * Remove the specified resource from storage.
 */
public function destroy(string $id)
{
    $alimentaire = Alimentaire::findOrFail($id);
    $alimentaire->ingredient()->detach();
    $alimentaire->size()->detach();
    $alimentaire->supplement()->detach();

    $alimentaire->delete();

    
    return redirect()->route('alimentaires.index')->with('success', 'Aliment supprimé avec succès');
}
gych's avatar

Oke just to clarify, is the only issue you're still having that the checkbox ticks another checkbox?

  • Does saving work now?
Gervis_Andjoua's avatar

@gych yes the only issue is the checkbox ticks another checkbox . But saving work correctly

gych's avatar

Ok good try this code, I've changed value to ingredient->id because using index as value might cause some issues. Because the index for an ingredient in the loop can be different when you add other ingredients, the id not.

@foreach($ingredients as $index => $ingredient)
    <input
        class="form-check-input"
        type="checkbox"
        id="ingredient_id"
        value="{{ $ingredient->id }}"
        name="ingredients[]" {{ in_array($ingredient->id, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}
    > 
    {{ $ingredient->title }} {{ $ingredient->price}}
1 like
Gervis_Andjoua's avatar

@gych now when i unheck a box it works .But when i come back to modify it sends me back all the checked boxes...

gych's avatar

That's somehow caused because of this condition to check the boxes

{{ in_array($ingredient->id, old('ingredients', $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : [])) ? 'checked' : '' }}

To test when you try this do you get the same issue?

@foreach($ingredients as $index => $ingredient)
    <input
        class="form-check-input"
        type="checkbox"
        id="ingredient_id"
        value="{{ $ingredient->id }}"
        name="ingredients[]" {{ in_array($ingredient->id, $alimentaire->ingredient ? $alimentaire->ingredient->pluck('id')->toArray() : []) ? 'checked' : '' }}
    > 
    {{ $ingredient->title }} {{ $ingredient->price}}
gych's avatar

Ok it seems like all ingredients in the loop are now set in alimentaire-ingredient

Can you debug this with dd($alimentaire->ingredient) to double check this?

gych's avatar

Yes before you return the view where you see all the boxes checked

Gervis_Andjoua's avatar

this response after debuging

#items: array:3 [▼ 0 => App\Models Ingredient {#1388 ▼ #connection: "mysql" #table: "ingredients" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #escapeWhenCastingToString: false #attributes: array:6 [▶] #original: array:10 [▶] #changes: [] #casts: [] #classCastCache: [] #attributeCastCache: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▶] #touches: [] +timestamps: true +usesUniqueIds: false #hidden: [] #visible: [] #fillable: [] #guarded: [] } 1 => App\Models Ingredient {#1465 ▼ #connection: "mysql" #table: "ingredients" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #escapeWhenCastingToString: false #attributes: array:6 [▶] #original: array:10 [▶] #changes: [] #casts: [] #classCastCache: [] #attributeCastCache: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▶] #touches: [] +timestamps: true +usesUniqueIds: false #hidden: [] #visible: [] #fillable: [] #guarded: [] } 2 => App\Models Ingredient {#1464 ▼ #connection: "mysql" #table: "ingredients" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #escapeWhenCastingToString: false #attributes: array:6 [▼ "id" => 3 "title" => "Laitue" "status" => 1 "price" => "10 DH" "created_at" => "2024-02-26 11:19:26" "updated_at" => "2024-02-26 11:19:26" ] #original: array:10 [▶] #changes: [] #casts: [] #classCastCache: [] #attributeCastCache: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: array:1 [▶] #touches: [] +timestamps: true +usesUniqueIds: false #hidden: [] #visible: [] #fillable: [] #guarded: [] }

gych's avatar

So all ingredients are set as relation to alimentaire->ingredient right?

Try to uncheck the ingredients, save and see if they're still checked

Gervis_Andjoua's avatar

@gych Yes all ingredient are set as relation to alimentaire->ingredient . they're all checked

gych's avatar

Try to detach them from the relation, you can try to uncheck them and save again or just use detach() like you use in your destroy method. Then after that test again.

gych's avatar

Yes that's possible but just use it once to detach all and remove it afterwards.

$alimentaire->ingredient()->detach();
gych's avatar

Strange can't directly see what's causing this behavior. Can you share the controller edit method?

Gervis_Andjoua's avatar

@gych

this is controller method edit

public function edit(string $id) { // Récupérer l'alimentaire à éditer depuis la base de données $alimentaire = Alimentaire::findOrFail($id);

    // Récupérer toutes les catégories, les ingrédients, les tailles et les suppléments depuis la base de données
    $categories = Category::all();
    $ingredients = Ingredient::select('title','id','price')->get();
    
    $sizes = Size::select('taille','id','price')->get();
    $supplements = Supplement::select('title','id','price')->get();

    // Passer les données récupérées et l'alimentaire à éditer à la vue correspondante
    return view('alimentaires.edit', compact('alimentaire', 'categories', 'ingredients', 'sizes', 'supplements'));
}
gych's avatar

Oke for testing try to add detach directly in the edit method

public function edit(string $id) { 
	// Récupérer l'alimentaire à éditer depuis la base de données 
	$alimentaire = Alimentaire::findOrFail($id);

	$alimentaire->ingredient()->detach();

    // Récupérer toutes les catégories, les ingrédients, les tailles et les suppléments depuis la base de données
    $categories = Category::all();
    $ingredients = Ingredient::select('title','id','price')->get();
    
    $sizes = Size::select('taille','id','price')->get();
    $supplements = Supplement::select('title','id','price')->get();

    // Passer les données récupérées et l'alimentaire à éditer à la vue correspondante
    return view('alimentaires.edit', compact('alimentaire', 'categories', 'ingredients', 'sizes', 'supplements'));
}
gych's avatar
gych
Best Answer
Level 29

No just add $alimentaire->ingredient()->detach(); to the edit method like I showed in my previous reply. Its only for testing purposes and to remove all the relations that might be previously set by incorrect code.

And let me know if after this the checkboxes are still checked or not.

After testing this you can remove $alimentaire->ingredient()->detach(); again from the edit method.

1 like
gych's avatar

Oke good but did you also remove the detach again from the edit method? Because if you leave it there it will clear all the relations each time you open the edit page.

Do some test by editing, saving and going back to the edit page to be 100% sure everything works as it should.

gych's avatar

Great ! I'm glad it works :)

1 like

Please or to participate in this conversation.