My Route:
Route::controller('admin' , 'CategoriesController');
Controller:
<?php
class CategoriesController extends BaseController {
/**
* Display a listing of the resource.
* GET /categories
*
* @return Response
*/
public function __construct() {
$this->beforeFilter('csrf', array('on' =>'post' ));
}
public function getIndex()
{
return View::make('categories.index')
->with('categories', Category::all());
}
/**
* Show the form for creating a new resource.
* GET /categories/create
*
* @return Response
*/
public function postCreate()
{
$validator = Validator::make(Input::all(), Category::$rules);
if ($validator->passes()) {
$category = new Category;
$category->name = Input::get('name');
$category->save();
return Redirect::to('admin/categories/index')
->with('message' , 'Category created');
}
return Redirect::to('admin/categories/index')
->with('message' , 'Something went wrong')
->withErrors($validator)
->withInput();
}
/**
* Remove the specified resource from storage.
* DELETE /categories/{id}
*
* @param int $id
* @return Response
*/
public function postDestroy()
{
$category = Category::find(Input::get('id'));
if ($category){
$category->delete();
return Redirect::to('admin/categories/index')
->with('message' , 'category deleted');
}
return Redirect::to('admin/categories/index')
->with('message' , 'something went wronng');
}
}
Model:
<?php
class Category extends \Eloquent {
protected $fillable = array('name');
public static $rules = array('name'=>'required|min:3');
}
view/index.blade :
@section('content')
<div id="admin">
<h1>Categories Admin panel</h1>
<p>Here you can view, delete, and create new categories.</p>
<h2>Categories</h2>
<ul>
@foreach($categories as $category)
<li>
{{ $category->name }}
{{ Form::open(array('url'=>'admin/categories/destroy', 'class' => 'form-inline'))}}
{{ Form::hidden('id' , $category->id) }}
{{ Form::submit('delete')}}
{{ Form::close();}}
</li>
@endforeach
</ul>
<h2>Create New Category</h2>
@if($errors->has)
<div id="form-errors">
<p>The following erros</p>
<ul>
@foreach($errors->all() as $error)
<li>{{ $errors }}</li>
@endforeach
</ul>
</div><!--end form-errors-->
@endif
{{ Form::open(array('url'=>'admin/categories/create'))}}
<p>
{{ Form::label('name')}}
{{ Form::text('name')}}
</p>
{{ Form::submit('Create Category', array('class' => 'secodary-cart-btn'))}}
{{ Form::close()}}
</div><!--end admin-->
@stop
The Problem is: When I run this code in my browser it show undefined variable: category in index.blade.php.