Last active
April 13, 2017 22:37
-
-
Save dilantha/8089372 to your computer and use it in GitHub Desktop.
Laravel related model data population for multiple checkboxes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Product extends Eloquent { | |
public function categories() | |
{ | |
return $this->belongsToMany('Category'); | |
} | |
} | |
<?php | |
class Category extends Eloquent { | |
public function products() | |
{ | |
return $this->belongsToMany('Product'); | |
} | |
} | |
// Product edit | |
/** | |
* Show the form for editing the specified resource. | |
* | |
* @param int $id | |
* @return Response | |
*/ | |
public function edit($id) | |
{ | |
$product = $this->product->find($id); | |
if (is_null($product)) | |
{ | |
return Redirect::route('products.index'); | |
} | |
$this->data['product'] = $product; | |
$this->data['categories'] = Category::all(); | |
$selectedCategories = $product->categories()->get()->toArray(); | |
$selectedCategories = array_pluck($selectedCategories, 'id'); | |
$this->data['selectedCategories'] = $selectedCategories; | |
return View::make('products.edit', $this->data); | |
} | |
// form | |
<legend>Categories</legend> | |
@foreach($categories as $category) | |
<div class="checkbox"> | |
<label> | |
@if(in_array($category->id, $selectedCategories)) | |
{{ Form::checkbox('categories[]', $category->id, true) }} | |
@else | |
{{ Form::checkbox('categories[]', $category->id, false) }} | |
@endif | |
{{ $category->name }} | |
</label> | |
</div> | |
@endforeach |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment