Create a CRUD Application with Laravel 5.2 part-7

 

Editing user information

Now as we learned how easy it is to add and list users. Let’s jump into editing a user. In our list users view we have the edit link with the following code:

{{ link_to_route('users.edit', 'Edit', array($user->id), array('class' => 'btn btn-info')) }}

Here, the link_to_route function will generate a link /users/<id>/edit, which will call the resourceful Controller user, and Controller will bind it with the edit method.

So here is the code for editing a user. First of all we are handling the edit request by adding the following code to our UsersController:

    public function edit($id)
    {
        $user = User::find($id);
        if (is_null($user))
        {
            return Redirect::route('users.index');
        }
        return View::make('users.edit', compact('user'));
    }

So when the edit request is fired, it will hit the edit method described in the preceding code snippet. We would need to find whether the user exists in the database. So we use our user model to query the ID using the following line of code:

$user = User::find($id);

Eloquent object’s find method will query the database just like a normal SQL.

Select * from users where id = $id

Then we will check whether the object we received is empty or not. If it is empty, we would just redirect the user to our list user’s interface. If it is not empty, we would direct the user to the user’s edit view with our Eloquent object as a compact array.




So let’s create our edit user view at app/resouces/users/edit.blade.php, as follows:

@extends('users.scaffold')

@section('main')

<h1>Edit User</h1>
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.update', $user->id))) }}
    <ul>
        <li>
            {{ Form::label('username', 'Username:') }}
            {{ Form::text('username') }}
        </li>
        <li>
            {{ Form::label('password', 'Password:') }}
            {{ Form::text('password') }}
        </li>
        <li>
            {{ Form::label('email', 'Email:') }}
            {{ Form::text('email') }}
        </li>
        <li>
            {{ Form::label('phone', 'Phone:') }}
            {{ Form::text('phone') }}
        </li>
        <li>
            {{ Form::label('name', 'Name:') }}
            {{ Form::text('name') }}
        </li>
        <li>
            {{ Form::submit('Update', array('class' => 'btn btn-info')) }}
            {{ link_to_route('users.show', 'Cancel', $user->id, array('class' => 'btn')) }}
        </li>
    </ul>
{{ Form::close() }}

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

@stop

Here we are extending our users’ layout as always and defining the main section. Now in the main section, we are using the Form helper to generate a proper REST request for our controller.

{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.update', $user->id))) }}

Now, you may have not dealt with the method PATCH as we only know of two protocols, GET and POST, as most browsers generally support only these two methods. The REST method for editing is PATCH, and what Laravel does is that it creates a hidden token so it knows which method to call. So the preceding code generates the following code:

<form method="POST" action="http://ch3.sr/users/1" accept-charset="UTF-8">
<input name="_method" type="hidden" value="PATCH">

It actually fires a POST method for browsers that are not capable for handling the PATCH method. Now, when a user submits this form, it will send a request to the update method of UsersController via the resourceful Controller we set in routes.php.

Here is the update method of UsersController:

public function update($id)
    {
        $input = Input::all();
        $validation = Validator::make($input, User::$rules);
        if ($validation->passes())
        {
            $user = User::find($id);
            $user->update($input);
            return Redirect::route('users.show', $id);
        }
return Redirect::route('users.edit', $id)
            ->withInput()
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
    }

Here Laravel will pass the ID of the user we are editing in the update method. We can use this ID to find the user via our user model’s Eloquent object’s find method. Then we will update the Eloquent object with an input array just like we did in the insert operation.
Deleting user information

To delete a user we can use the destroy method. If you go to our user lists view, you can find the following delete link’s generation code:

{{ Form::open(array('method' => 'DELETE', 'route' => array('users.destroy', $user->id))) }}
{{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}

The preceding code is handled by Laravel similar to the way in which it handles the PATCH method. Laravel will generate a post request with the hidden method token set as PATCH, which it can recognize when it hits the Laravel request object.

At UsersController this request will hit the destroy() method as follows:

    public function destroy($id)
    {
        User::find($id)->delete();
        return Redirect::route('users.index');
    }

Laravel will directly send id to the destroy method, so all we have to do is use our user model and delete the record with its delete method. If you noticed Eloquent allows us to chain methods. Isn’t it sweet? So there would be no queries but just one line to delete a user.

That’s one of the reasons to use Eloquent objects in your projects. It allows you to quickly interact with the database and you can use objects to match your business logic.
Adding pagination to our list users

One of the painful tasks most developers face often is that of pagination. With Laravel it’s no more the case, as Laravel provides a simple approach to set pagination to your pages.

Let’s try to implement pagination to our list user’s method. To set pagination we can use the paginate method with Laravel’s Eloquent object. Here is how we can do that:

public function index()
{
  $users = User::paginate(5);
  return View::make('users.index', compact('users'));
}

The preceding code is the index method of the UsersController class, which we were using previously for getting all the users with User::all(). We just used the paginate method to find five records from the database. Now in our list users view, we can use the following code to display pagination links:

{{ echo $users->links(); }}

Here the links() method will generate pagination links for you. And best part, Laravel will manage the code for pagination. So all you have to do is use paginate method with your eloquent object and links method to display generated links.


Wrapping up

So we have set up our simple CRUD application and now we know how easy it is with Laravel to set up CRUD operations. We have seen Eloquent Laravel’s database ORM that makes working with a database simple and easy. We have learned how to list users, create new users, edit users, delete users, and how to add pagination to our application.