Skip to content

Instantly share code, notes, and snippets.

@mikeritter
Last active February 28, 2017 20:00
Show Gist options
  • Save mikeritter/efa50a3d123d836eb862 to your computer and use it in GitHub Desktop.
Save mikeritter/efa50a3d123d836eb862 to your computer and use it in GitHub Desktop.
Laravel Eloquent Edit Form with Associated Checkboxes Checked
/*
* The issue at hand is how to show checked boxes in
* a Laravel edit form using Eloquent models.
*/
/*
* My Models
*
*/
// models/Product.php
class Product extends Eloquent{
...
public function categories(){
return $this->belongsToMany('Category');
}
...
}
// models/Category.php
class Category extends Eloquent{
...
public function products(){
return $this->belongsToMany('Product');
}
...
}
/*
* My controller for Product class
*
*/
// controllers/ProductAdminController.php
class ProductAdminController extends BaseController{
protected $product;
protected $rules;
protected $category;
/**
* Construct the object from model
*
*/
public function __construct(Product $product, Category $category)
{
$this->product = $product;
$this->category = $category;
}
...
public function edit($id)
{
// Pass the Product with the given id and Categor[ies] with an eagr-load of associated Products
return View::make('admin.products.edit')->with('product',$this->product->find($id))->with('categories',$this->category->with('products')->get());
}
...
}
/*
* Blade Edit View
*
*/
// views/admin/products/edit.blade.php
{{ Form::model($product,array('route' => array('admin.products.update',$product->id),'method' => 'put')) }}
...
<fieldset>
<legend>Categories</legend>
<ul>
// loop through my categories which are eager-loaded with an array of associated products
@foreach($categories as $cat)
// if this category contains an instance of the product we're editing set the checkbox to true
@if($cat->products->contains($product))
<li>{{ Form::checkbox('categories[]',$cat->id,true,array('id'=>"category_$cat->id")) }}{{ Form::label("category_$cat->id",$cat->title) }}</li>
// otherwise the checkbox value is null
@else
<li>{{ Form::checkbox('categories[]',$cat->id,null,array('id'=>"category_$cat->id")) }}{{ Form::label("category_$cat->id",$cat->title) }}</li>
@endif
@endforeach
</ul>
</fieldset>
...
{{ Form::close() }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment