Home » Tutorials

Category Archives: Tutorials

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

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.

The End. https://www.dunebook.com/

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

 

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

As you can see, resource Controller really makes your work easy. You don’t have to create lots of routes. Also Laravel ‘s artisan-command-line generator can generate resourceful Controllers, so you will write very less boilerplate code. And you can also use the following command to view the list of all the routes in your project from the root of your project, launching command line:

$ php artisan routes

Now let’s get back to our basic task, that is, reading users. Well now we know that we have UserController.php at /app/controller with the index method, which will be executed when somebody launches http://localhost/laravel/public/users. So let’s edit the Controller file to fetch data from the database.

Well as you might remember, we will need a Model to do that. But how do we define one and what’s the use of Models? You might be wondering, can’t we just run the queries? Well Laravel does support queries through the DB class, but Laravel also has Eloquent that gives us our table as a database object, and what’s great about object is that we can play around with its methods. So let’s create a Model.

If you check your path /app/User.php, you will already have a user Model defined. It’s there because Laravel provides us with some basic user authentication. Generally you can create your Model using the following code:

class User extends Eloquent {}

Now in your controller you can fetch the user object using the following code:

$users = User::all();
$users->toarray();

Yeah! It’s that simple. No database connection! No queries! Isn’t it magic? It’s the simplicity of Eloquent objects that many people like in Laravel.

But you have the following questions, right?

  • How does Model know which table to fetch?
  • How does Controller know what is a user?
  • How does the fetching of user records work? We don’t have all the methods in the User class, so how did it work?

Well models in Laravel use a lowercase, plural name of the class as the table name unless another name is explicitly specified. So in our case, User was converted to a lowercase user and used as a table to bind with the User class.

Models are automatically loaded by Laravel, so you don’t have to include the reference of the Model file. Each Model inherits an Eloquent instance that resolves methods defined in the model.php file at vendor/Laravel/framework/src/Illumininate/Database/Eloquent/ like all, insert, update, delete and our user class inherit those methods and as a result of this, we can fetch records via User::all().

So now let’s try to fetch users from our database via the Eloquent object. I am updating the index method in our app/controllers/UsersController.php as it’s the method responsible as per the REST convention we are using via resource Controller.

public function index()
  {

        $users = User::all();

return View::make(‘users.index’, compact(‘users’));
}

 

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

Listing the users – read users from database

Let’s read users from the database. We would need to follow the steps described to read users from database:

  • A route that will lead to our page
  • A controller that will handle our method
  • The Eloquent Model that will connect to the database
  • A view that will display our records in the template

So let’s create our route at /app/http/routes.php. Add the following line to the routes.php file:

Route::resource('users', 'UserController');

If you have noticed previously, we had Route::get for displaying our page Controller. But now we are using resource. So what’s the difference?

In general we face two types of requests during web projects: GET and POST. We generally use these HTTP request types to manipulate our pages, that is, you will check whether the page has any POST variables set; if not, you will display the user form to enter data. As a user submits the form, it will send a POST request as we generally define the <form method="post"> tag in our pages. Now based on page’s request type, we set the code to perform actions such as inserting user data into our database or filtering records.

What Laravel provides us is that we can simply tap into either a GET or POST request via routes and send it to the appropriate method. Here is an example for that:

Route::get('/register', 'UserController@showUserRegistration');
Route::post('/register', 'UserController@saveUser');

See the difference here is we are registering the same URL, /register, but we are defining its GET method so Laravel can call UserController class’ showUserRegistration method. If it’s the POST method, Laravel should call the saveUser method of the UserController class.

You might be wondering what’s the benefit of it? Well six months later if you want to know how something’s happening in your app, you can just check out the routes.php file and guess which Controller and which method of Controller handles the part you are interested in, developing it further or solving some bug. Even some other developer who is not used to your project will be able to understand how things work and can easily help move your project. This is because he would be able to somewhat understand the structure of your application by checking routes.php.

Now imagine the routes you will need for editing, deleting, or displaying a user. Resource Controller will save you from this trouble. A single line of route will map multiple restful actions with our resource Controller. It will automatically map the following actions with HTTP verbs:

HTTP VERB ACTION
GET READ
POST CREATE
PUT UPDATE
DELETE DELETE

On top of that you can actually generate your Controller via a simple command-line artisan using the following command:

$ php artisan make:controller usercontroller

This will generate UsersController.php with all the RESTful empty methods, so you will have an empty structure to play with. Here is what we will have after the preceding command:

class UserController extends BaseController {

  /**
   * Display a listing of the resource.
   *
   * @return Response
   */
  public function index()
  {
    //
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return Response
   */
  public function create()
  {
    //
  }

  /**
   * Store a newly created resource in storage.
   *
   * @return Response
   */
  public function store()
  {
    //
  }

  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return Response
   */
  public function show($id)
  {
    //
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return Response
   */
  public function edit($id)
  {
    //
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function update($id)
  {
    //
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function destroy($id)
  {
    //
  }
  
}

Now let’s try to understand what our single line route declaration created relationship with our generated Controller.
HTTP VERB Path Controller Action/method
GET /Users Index
GET /Users/create Create
POST /Users Store
GET /Users/{id} Show (individual record)
GET /Users/{id}/edit Edit
PUT /Users/{id} Update
DELETE /Users/{id} Destroy

Source: https://www.dunebook.com

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

let’s create a simple CRUD application with Laravel . we have updated This tutorial to laravel 5.2 . The application we want to create will manage the users of our application. We will create the following list of features for our application:

  • List users (read users from the database)
  • Create new users
  • Edit user information
  • Delete user information
  • Adding pagination to the list of users

Now to start off with things, we would need to set up a database. So if you have phpMyAdmin installed with your local web server setup, head over to http://localhost/phpmyadmin; if you don’t have phpMyAdmin installed, use the MySQL admin tool workbench to connect with your database and create a new database.

Requirements -> html form –> please install this and follow instructions from official site
Now we need to configure Laravel to connect with our database. So head over to your Laravel application folder, open config/database.php, change the MySQL array, and match your current database settings. Here is the MySQL database array from database.php file:

‘mysql’ => array(
‘driver’ => ‘mysql’,
‘host’ => ‘localhost’,
‘database’ => ”,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
),

Now we are ready to work with the database in our application. Let’s first create the database table Users via the following SQL queries from phpMyAdmin or any MySQL database admin tool;

CREATE TABLE IF NOT EXISTS ‘users’ (
‘id’ int(10) unsigned NOT NULL AUTO_INCREMENT,
‘username’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘password’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
’email’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘phone’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘name’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘created_at’ timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’,
‘updated_at’ timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’,
PRIMARY KEY (‘id’)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

Now let’s seed some data into the Users table so when we fetch the users we won’t get empty results. Run the following queries into your database admin tool:

INSERT INTO ‘users’ (‘id’, ‘username’, ‘password’, ’email’, ‘phone’, ‘name’, ‘created_at’, ‘updated_at’) VALUES
(1, ‘john’, ‘johndoe’, ‘johndoe@gmail.com’, ‘123456’, ‘John’, ‘2013-06-07 08:13:28’, ‘2013-06-07 08:13:28’),
(2, ‘amy’, ‘amy.deg’, ‘amy@outlook.com’, ‘1234567’, ‘amy’, ‘2013-06-07 08:14:49’, ‘2013-06-07 08:14:49’);

Note

Later we will see how we can manage our database via Laravel 4’s powerful migrations features. At the end of this chapter, I will introduce you to why it’s not a good practice to manually create SQL queries and make changes to the database structure. And I know that passwords should not be plain too!

Source : https://www.dunebook.com

Laravel 5 : Learn Easy

Laravel 5 Learn EasyFrom the New File Structure to Method Injection, Everything Explained (Sanjib Sinha).

Web Programming Simplified Series
This series is, basically, meant for the beginners who just want to make their hands dirty with codes and try to be a good web programmer! Intermediate and Advanced web programmers may find some parts thought provoking

Prologue to Laravel 5.2
Well, this will be a fairly good repetition if I am going to tell you, what Laravel is! Even if you are a beginner, you have already heard about what Laravel is – an ubiquitous and omnipresent intelligent PHP framework which has stormed the PHP world with a lot of modular varieties in its code repositories.
At a glance Laravel 5 Onwards
Laravel : An MVC Framework
MVC = Model-View-Controller
Software structure with emphasize on Modularity
Model : Application Data and Function
View : Representation of Output, e.g. HTML
Controller : Interacts with user, model and view

It has traversed a fairly long way in a very short period of time and won PHP developer’s hearts with one after another strong blows.

Laravel 5.2 Installation

Server Requirements

The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the Laravel Homestead virtual machine, so it’s highly recommended that you use Homestead as your local Laravel development environment.

However, if you are not using Homestead, you will need to make sure your server meets the following requirements:

PHP >= 5.5.9
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension

Installing Laravel

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.
Via Laravel Installer

First, download the Laravel installer using Composer:

composer global require “laravel/installer”

Make sure to place the ~/.composer/vendor/bin directory (or the equivalent directory for your OS) in your PATH so the laravel executable can be located by your system.

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel’s dependencies already installed. This method of installation is much faster than installing via Composer:

laravel new blog

Via Composer Create-Project

Alternatively, you may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project –prefer-dist laravel/laravel blog

Configuration

All of the configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
Directory Permissions

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.
Application Key

The next thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer or the Laravel installer, this key has already been set for you by the php artisan key:generate command. Typically, this string should be 32 characters long. The key can be set in the .env environment file. If you have not renamed the .env.example file to .env, you should do that now. If the application key is not set, your user sessions and other encrypted data will not be secure!
Additional Configuration

Laravel needs almost no other configuration out of the box. You are free to get started developing! However, you may wish to review the config/app.php file and its documentation. It contains several options such as timezone and locale that you may wish to change according to your application.

You may also want to configure a few additional components of Laravel, such as:

Cache
Database
Session

Once Laravel is installed, you should also configure your local environment.
Source: https://laravel.com/docs/5.2

Laravel 5.1 Installation

Server Requirements

The Laravel framework has a few system requirements. Of course, all of these requirements are satisfied by the Laravel Homestead virtual machine:

PHP >= 5.5.9
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension

Installing Laravel

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.
Via Laravel Installer

First, download the Laravel installer using Composer:

composer global require “laravel/installer”

Make sure to place the ~/.composer/vendor/bin directory (or the equivalent directory for your OS) in your PATH so the laravel executable can be located by your system.

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel’s dependencies already installed. This method of installation is much faster than installing via Composer:

laravel new blog

Via Composer Create-Project

Alternatively, you may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project –prefer-dist laravel/laravel blog

Configuration

All of the configuration files for the Laravel framework are stored in the config directory. Each option is documented, so feel free to look through the files and get familiar with the options available to you.
Directory Permissions

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.
Application Key

The next thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer or the Laravel installer, this key has already been set for you by the php artisan key:generate command. Typically, this string should be 32 characters long. The key can be set in the .env environment file. If you have not renamed the .env.example file to .env, you should do that now. If the application key is not set, your user sessions and other encrypted data will not be secure!
Additional Configuration

Laravel needs almost no other configuration out of the box. You are free to get started developing! However, you may wish to review the config/app.php file and its documentation. It contains several options such as timezone and locale that you may wish to change according to your application.

You may also want to configure a few additional components of Laravel, such as:

Cache
Database
Session

Once Laravel is installed, you should also configure your local environment.
Source: https://laravel.com/docs/5.1