Home » Articles » Create a CRUD Application with Laravel 5.2 (Part-5)

Create a CRUD Application with Laravel 5.2 (Part-5)

Creating new users

Now as we have listed our users, let’s write the code for creating new users. To create a new user, we will need to create the Controller method and bind the view for displaying the new user form. We would need to create the Controller method for saving the user too. Now as we have bound the resourceful Controller, we don’t need to create separate routes for each of our request. Laravel will handle that part if we use REST methods.

So first let’s edit the controller at /app/http/controllers/UsersController.php to add a method for displaying the view:

    public function create()
    {
        return View::make('users.create');
    }

This will call a view at /app/resources/users/create.blade.php. So let’s define our create.blade.php view as follows:

@extends('layouts.users')

@section('main')

<h1>Create User</h1>

{{ Form::open(array('route' => 'users.store')) }}
    <ul>

        <li>
            {{ Form::label('name', 'Name:') }}
            {{ Form::text('name') }}
        </li>

        <li>
            {{ Form::label('username', 'Username:') }}
            {{ Form::text('username') }}
        </li>

        <li>
            {{ Form::label('password', 'Password:') }}
            {{ Form::password('password') }}
        </li>

        <li>
            {{ Form::label('password', 'Confirm Password:') }}
            {{ Form::password('password_confirmation') }}
        </li>        

        <li>
            {{ Form::label('email', 'Email:') }}
            {{ Form::text('email') }}
        </li>

        <li>
            {{ Form::label('phone', 'Phone:') }}
            {{ Form::text('phone') }}
        </li>


        <li>
            {{ Form::submit('Submit', array('class' => 'btn')) }}
        </li>
    </ul>
{{ Form::close() }}

@if ($errors->any())
    <ul>
        {{ implode('', $errors->all('<li class="error">:message</li>')) }}
    </ul>
@endif

@stop

Let’s try to understand our preceding view. Here we are extending the users layout we created in our List Users section. Now in the main section, we are using Laravel’s Form helper to generate our form. This helper generates HTML code via its methods such as label, text, and submit.

Refer to the following code:

{{ Form::open(array('route' => 'users.store')) }}

The preceding code will generate the following HTML code:

<form method="POST" action="http://localhost/users" accept-charset="UTF-8">

As you can see it’s really convenient for us to not worry about linking things correctly. Now let’s create our store method to store our form data into our users table:

public function store()
    {
        $input = Input::all();
        $validation = Validator::make($input, User::$rules);

        if ($validation->passes())
        {
            User::create($input);

            return Redirect::route('users.index');
        }

        return Redirect::route('users.create')
            ->withInput()
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
    }

Here we are first validating all the input that came from the user. The Input::all () function fetches all the $_GET and $_POST variables and puts it into a single array. The reason why we are creating the single input array is so we can check that array against validation rules’ array. Laravel provides a very simple Validation class that can be used to check validations. We could use it to check whether validations provided in the rules array are followed by the input array by using the following line of code:

$validation = Validator::make ($input, User::$rules);

Rules can be defined in an array with validation attributes separated by the column “|”. Here we are using User::$rules where User is our Model and it will have following code:

class User extends Eloquent {

  protected $guarded = array('id');
  protected $fillable = array('name', 'email');

  public static $rules = array(
    'name' => 'required|min:5',
    'email' => 'required|email'
  );
}

As you can observe we have defined two rules mainly for name and e-mail input fields. If you are wondering about $guarded and $fillable variables, these variables are used to prevent mass assignment. When you pass an array into your Model’s create and update methods, Laravel tries to match the right columns and sets values in the database. Now for instance, if a malicious user sends a hidden input named id and changes his ID via the update method of your form, it could be a huge security hole; to prevent this, we should define the $guarded and $fillable arrays. The $guarded array will guard the columns defined in the guarded array, that is, it will prevent anyone from changing values in that column. The $fillable array will only allow elements defined in $fillable to be updated.

Now we can use the $validation instance we created to check for validations.

$result = $validation->passes();
echo $result; // True or false

If you see our code now, we are checking for validation via the passes() method in our Store() method of UserController. Now if validation gets passed, we can use our user Model to store data into our database. All you need to do is call the Create method of the Model class with the $input array. So refer to the following code:

User::create($input);

The preceding code will store our $input array into the database; yes, it’s equivalent to your SQL query.

Insert into user(name,password,email,city) values (x,x,..,x);

Here we have to fill either the $fillable or $guarded array in the model, otherwise, Laravel will throw a mass assignment exception. Laravel’s Eloquent object automatically matches our input array with the database and creates a query based on our input array. Don’t you think this is a simple way to store input into the database? If user data is inserted, we are using Laravel’s redirect method to redirect it to our list of users’ pages. If validation fails, we are sending all of the input with errors from the validation object into our create users form.

Source: https://www.dunebook.com

 

Leave a comment

Your email address will not be published. Required fields are marked *