I'm making a simple add products and categories. Where categories have plenty of products. Here's my code:
In create category table:
Schema::create('categories', function($table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
In create product table:
Schema::create('products', function($table){
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('title');
$table->timestamps();
});
In product controller:
public function postCreate(){
$validator = Validator::make(Input::all(), Product::$rules);
if($validator->passes()){
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/product/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
Then in my index.blade.php
{{ Form::open(array('url'=>'admin/products/create', 'files'=>true)) }}
<p>
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories) }}
</p>
<p>
{{ Form::label('title') }}
{{ Form::text('title') }}
</p>
{{ Form::submit('Create Product', array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
In my route:
Route::controller('admin/categories', 'CategoriesController');
Route::controller('admin/products', 'ProductsController');
The problem here is that, if there is no item/data in the Category table, the product page, will display but of course there is no data in my select box since there is no category data. But if I put some data in the Category table, the product page will display an error "Whoops, looks like something went wrong.". I believe that the problem is on the foreign key which is not getting the data in Category table. Could you guys help me put out where is the problem in my code? and how to make it work.
Here's what show up after turning on the debug at app.php
class ProductsController extends BaseController{
public function __construct() {
$this->beforeFilter('csrf', array('on'=>'post'));
}
public function getIndex(){
$categories = array();
foreach (Category::all() as $category) {
$categories[$category->id] = $categories->name;
}
return View::make('products.index')
ErrorException (E_NOTICE) Trying to get property of non-object
Foreach condition was hightlighted. Please advise whats wrong with this code.