Jump to: navigation, search

Setting up one-page CRUD

I will be using the AdminController user methods for examples in this page. You can look to that file to follow along.

Helpful Links

  1. View Crud Describes the entirety of the CRUD methods.
  2. Response Post This is used to handle the post data.
  3. Response Ajax What we will use to handle the ajax submits.


  1. Parent page: The page that will house the nav stack.
  2. Child Page: A page that is ajax loaded into the parent page.


Tips and Tricks


In this page you will see references to "MultiView". This is a unique way to display data in the one page crud. It is designed primarily for displaying data on pivot tables. It differs in that instead of showing every row in the returned collection, it shows a row for each primary object. The second column then shows all objects of a certain record.


If you want to display all roles for each user, users would be the primary column and would each have their own row. The roles would then be the second column and the page would display each role that the user is in. You can view this in your site by going to /admin.

Form Fields

There are a few supported options for form fields. Below, I will go over them and give example syntax. For detailed information, look at the View Crud page.


  1. Property of the object
  2. Type of input
  3. Array of data for select input
  4. Required flag
  5. Placeholder text


One thing to note is that the fifth parameter on any form field addition is the placeholder. If none is supplied, the column name (first parameter) will be used by default.


Normally with text, you will only need to submit the first two parameters.

  1. Crud::addFormField(column_name, text);

  1. <input type="text" name="column_name" id="input_column_name" placeholder="Column_name" />


Normally with email, you will only need to submit the first two parameters.

  1. Crud::addFormField(column_name, email, null, true, 'Email Address');

  1. <input type="email" name="column_name" id="input_column_name" required="required" placeholder="Email Address" />


Normally with textareas, you will only need to submit the first two parameters.

  1. Crus::addFormField(column_name, textarea);

  1. <textarea name="column_name" id="input_column_name" placeholder="Column_name" cols="50" rows="10"></textarea>

Select and Multi-Select

The select type requires the third parameter. You can use arrayToSelect() to format the array correctly.

  1. $selectArray = $this->arrayToSelect($users, 'id', 'username', 'Select a username');
  2. Crud::addFormField(column_name, select, $selectArray);

  1. <select name="column_name" id="input_column_name">
  2.         <option value="0">Select a username</option>
  3.         <option value="1">User 1</option>
  4. </select>

The Pages

The pages for any one page crud consists of 4 methods. They cover setting up the get method, the post method and the delete method as well as the controller for the parent page.

The Parent Page

The parent page only needs to contain a view (normally). The view will set up the nav stack that will be used to call the child pages.

Full Code
  1. <div class="row-fluid">
  2.         <div class="span2">
  3.                 <ul class="nav nav-tabs nav-stacked">
  4.                         <li class="nav-title">Permissions</li>
  5.                         <li><a href="javascript: void(0);" class="ajaxLink" id="users">Users</a></li>
  6.                         <li><a href="javascript: void(0);" class="ajaxLink" id="actions">Actions</a></li>
  7.                 </ul>
  8.         </div>
  9.         <div class="span10">
  10.                 <div id="ajaxContent">
  11.                         Loading
  12.                 </div>
  13.         </div>
  14. </div>
  15. <script>
  16.         @section('onReadyJs')
  17.                 $.AjaxLeftTabs('/admin/', 'users');
  18.         @endsection
  19. </script>

Lets go through this one-by-one.

The nav stack

  1. <ul class="nav nav-tabs nav-stacked">
  2.         <li class="nav-title">Permissions</li>
  3.         <li><a href="javascript: void(0);" class="ajaxLink" id="users">Users</a></li>
  4.         <li><a href="javascript: void(0);" class="ajaxLink" id="actions">Actions</a></li>
  5. </ul>

The nav stack is how we let the ajax load know what page we want to see. To create an entry you need 3 things.

  1. The li entry must have the class "ajaxLink"
  2. The id should be the name of your child methods
    • In this example, id="users" would mean that the child controller methods will be getUsers() and postUsers()
  3. The display text for the li


  1. <script>
  2.         @section('onReadyJs')
  3.                 $.AjaxLeftTabs('/admin/', 'users');
  4.         @endsection
  5. </script>

The ajax section is used to handle the ajax loading of the page you specify. The meat of AjaxLeftTabs is located in public/js/master.js. The parameters require two things.

  1. The URL for your page. All methods will be appended to this.
  2. The default entry to load.

The Child Pages

The child pages have no views at all. The views are taken care of by app/views/helpers/crud.blade.php. All you will need to do is set up the 3 controller methods per page.

The Get method

The get method for a CRUD page, sets up the View Crud helper. A few things are required.

  1. Title
  2. Sort Property
  3. Delete Flag or Delete Link with Delete Property
  4. Resources
  5. Display Fields
  6. Form Fields

I personally chose to separate this into 3 chains. 1 for the base details (Title, Sort Property, Delete Details, Resources), 1 for the display fields and 1 for the form fields.

Example of the base details
  1. $users = User::orderBy('username', 'asc')->get();
  3. // Set up the one page crud main details
  4. Crud::setTitle('Users')
  5.          ->setSortProperty('username')
  6.          ->setDeleteLink('/admin/userdelete/')
  7.          ->setDeleteProperty('id')
  8.          ->setResources($users);

Example of the display fields
  1. // Add the display columns
  2. Crud::addDisplayField('username', '/profile/user/', 'id')
  3.          ->addDisplayField('email', 'mailto');

Example of the form fields
  1. // Add the form fields
  2. Crud::addFormField('username', 'text', null, true)
  3.          ->addFormField('email', 'email', null, true)
  4.          ->addFormField('firstName', 'text')
  5.          ->addFormField('lastName', 'text');

Full Example
  1. public function getUsers()
  2. {
  3.     $users = User::orderBy('username', 'asc')->get();
  5.     // Set up the one page crud main details
  6.     Crud::setTitle('Users')
  7.              ->setSortProperty('username')
  8.              ->setDeleteLink('/admin/userdelete/')
  9.              ->setDeleteProperty('id')
  10.              ->setResources($users);
  12.     // Add the display columns
  13.     Crud::addDisplayField('username', '/profile/user/', 'id')
  14.              ->addDisplayField('email', 'mailto');
  16.     // Add the form fields
  17.     Crud::addFormField('username', 'text', null, true)
  18.              ->addFormField('email', 'email', null, true)
  19.              ->addFormField('firstName', 'text')
  20.              ->addFormField('lastName', 'text');
  22.     // Set the view data
  23.     Crud::make();
  24. }

This gives us 26 lines and the entirety of the get method is completed. Not too bad all in all. Remember that the view is taken care of for you already.

Full Example
  1. public function getRoleusers()
  2. {
  3.     $users        = User::orderBy('username', 'asc')->get();
  4.     $roles        = User_Permission_Role::orderByNameAsc()->get();
  5.     $usersArray   = $this->arrayToSelect($users, 'id', 'username', 'Select a user');
  6.     $rolesArray   = $this->arrayToSelect($roles, 'id', 'name', 'None');
  8.     // Set up the one page crud
  9.     Crud::setTitle('Role Users')
  10.              ->setSortProperty('usernamename')
  11.              ->setDeleteFlag(false)
  12.              ->setMulti($users, 'roles')
  13.              ->setMultiColumns(array('Users', 'Roles'))
  14.              ->setMultiDetails(array('name' => 'username', 'field' => 'user_id'))
  15.              ->setMultiPropertyDetails(array('name' => 'name', 'field' => 'role_id'));
  17.     // Add the form fields
  18.     Crud::addFormField('user_id', 'select', $usersArray)
  19.              ->addFormField('role_id', 'multiselect', $rolesArray);
  21.     Crud::make();
  22. }

The Post method

The post method is what we will use to handle form submission. On a normal CRUD page, all this method has to do is determine whether it is saving or creating an object and process that request.

Full Example
  1. public function postUsers()
  2. {
  3.     $this->skipView();
  5.     // Set the input data
  6.     $input = e_array(Input::all());
  8.     if ($input != null) {
  9.         // Get the object
  10.         $newPassword       = Str::random(15, 'all');
  11.         $user              = (isset($input['id']) && strlen($input['id']) == 10 ? User::find($input['id']) : new User);
  12.         $user->username    = $input['username'];
  13.         $user->password    = (isset($input['id']) && strlen($input['id']) == 10 ? $user->password : $newPassword);
  14.         $user->email       = $input['email'];
  15.         $user->firstName   = $input['firstName'];
  16.         $user->lastName    = $input['lastName'];
  17.         $user->status_id   = 1;
  19.         // Attempt to save the object
  20.         $this->save($user);
  22.         // Handle errors
  23.         if ($this->errorCount() > 0) {
  24.             Ajax::addErrors($this->getErrors());
  25.         } else {
  26.            Ajax::setStatus('success')->addData('resource', $user->toArray());
  27.         }
  29.         // Send the response
  30.         return Ajax::sendResponse();
  31.     }
  32. }

I will go through the lines that may require assistance in understanding.

  3. This line is used to tell the BaseController to skip the view. This will stop it from trying to load any view for the post.
  6. Here, we sanitize the incoming data. Even though we control the form, it's better to be safe.
  8. We make sure that something was actually submitted.
10. This creates a random password in case this is a new user.
11. This is the meat of the method. This line checks to see if we are adding or editing a user. The strlen is only used for models using uniqueIds.
13. If this is an existing user, use the existing password, otherwise create a new one.
20. We use save() to make sure the model is handled properly.
24. If there are errors, we add the errors to the ajax response using addErrors() on the ajax response and getErrors() on the post response.
26. If there were no errors, we set the status of the ajax call. We also add the saved model to the ajax response.
30. Lastly, we send the response through ajax.

This is all that is needed for a base post method. You can do anything else you want in this method, but these are the parts that are required to let the Response Post and Response Ajax properly handle everything.


The Delete method

The last thing you will need is the delete method. This is only needed if your deleteFlag() is not set to false. The name of this method will be determined by your deleteLink(). In our example, the deletLink was set to /admin/userdelete. This means the method name would be getUserdelete.

Full Example
  1. public function getUserdelete($userId)
  2. {
  3.     $this->skipView();
  5.     $user = User::find($userId);
  6.     $user->delete();
  8.     return $this->redirect('back');
  9. }

All we normally do in this method is find the object and delete it. If the model being deleted has softDelete enabled, this will still handle that normally. The last thing this does is redirect back which just sends them back to the admin page (since users is the default). If you are doing this on a method that is not the default, point it to the ID.

  1. return $this->redirect('/admin#users');


When using this page in MultiView mode, you do not need a delete method. The post method takes care of all deleting and adding since you are only dealing with pivots.