Wednesday, 13 July 2016

Receiving data from form (Eloquent)

Eloquent

Let’s first of all have a look at Eloquent.
Eloquent is used to interact with the database. We have a corresponding model for every table.  It allows you to insert data in your table as well as apply any query to that. Before this you must make sure that you have configured your database explained in migration article.
By default the models are located in app folder. If you to go to the app folder you will see a User.php file, this is an already created model. Migration of user and model for that is already created because user is a part of many projects, you can just delete it if you don’t need it and make your own model.
Let’s create our first model, for that go to command prompt then go to the location of your project e.g. D:\wamp\www\bitspedia and type
php artisan make:model Users
It will create a model named as Users in app directory. Now if you open it you will see that a code has been generated.
You have to tell the model that what attributes can be changed by user. Like you don’t want your “id” to be changed by user as it is auto incremented primary key so you will write the all other attribute except id as written below in the code sample.
Eloquent assume that you have “created_at” and “updated_at” columns in your table. If you don’t have them set the time-stamp false.

<?php
namespace
App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
    protected $fillable = [
'name', 'subjects','gender', 'date_of_birth', 'phone_no',
];
//attributes user can change

public $timestamps = false; //table don’t includes “created_at” and “updated_at”
}
Remember that subjects, gender, date_of_birth and phone_no are the attributes of my table
users.

Route
Let’s set a route so that when form is submitted it gets to our method where we will get and store this data.

Route::post('storeUser','controllerUsers@store');
Controller
When you have created a form and model now you need to get that information from the form and save it in the database for that you have to create a function in your controller
so let’s create a controller named as controllerUsers
Go to controller folder located in Http folder further located in app folder e.g. D:\wamp\www\bitspedia\app\Http
Now create a new php file named as controllerUsers now you must add basics things for controller i.e.
<?php
namespace
App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Users;
use Request;
use DB;
}
class controllerBasics extends Controller
{
public function store()
{
$user = Request::all();
//getting all the data from form
Users::create($user);
//storing the data in database
$file = Request::file('image'); //temporary path
$destinationPath = 'D:\wamp\www\bitspedia\public\uploads';  
// path where want to store
$fileName = $file->getClientOriginalName(); //getting the orginal name
$path=Request::file('image')->move($destinationPath,$fileName);
//moving the image and giving it a name
 
$lastUser = Users::orderBy('id', 'desc')->first(); //getting the last added user

Users::where('id','=', $lastUser->id)->update(['image_path' => $path]); 
//update the image path of that user

}

}
All controllers are stored in App\Http\Controllers and we used DB because we will contact with database(use DB), Request will be used to get data from form(use Request) and Users is a model that we created earlier and it is located in app folder(use App\Users). All controllers must extend the base controller.
I have also created a store method. Its responsibility will be to get data from form and store it in database. First we received data from form. We fetched all the data from form and stored it in some variable “$user”
Then we saved the data in our database, here you saw the benefits of Eloquent. To save the data which we have received and saved in a variable $user we just used a single line .i.e Users::create($user); this will create a row in database.

Then we received the temporary path of image. Then we gave a path where we want our image to be stored. Then we got the original file name. Then we moved the file to our desired folder

The destination saved in our database was be temporary location so we felt the need to update it so we did it by getting the last user added in database and then updating its image path.

To fetch a specific data let’s say we want to fetch only name from the form
$user= Request::get('name');
Remember that name is a textfield in my form.
You can also use except to get data of all attributes except some of the attributes
$user = Request::
except(['name']);
 

Queries
You can also apply any query on it as I mentioned above, let’s apply some queries
To get all the data from table
$user = Users::get();
To get all the rows where name is equal to junaid
$user = Users::where('name','=', 'junaid')->get();
To delete all the rows where name is equal to junaid
$user = Users::where('name','=', 'junaid')->delete();
To get the first row from table where name is equal to junaid
$user = Users::where('name','=', 'junaid')->first();
To apply a double where clause
$user = Users::where('first_name', '=', 'junaid')->where('class','=', 'fsc')->get();
To update the row where name is equal to junaid
$user = Users::where('name', 'junaid')->update(['name' => 'asif']);
The name will be updated to asif
You can fetch data by any order too
$user = Users::orderBy('id', 'desc')->first();
This will fetch data in descending order by id, similarly you can fetch data by ascending too.


Forms

Form
Before we talk about “form” we need to make few changes, first of all edit composer.json file located in your project e.g. D:\wamp\www\bitspedia with notepad you will see the following code written
"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*"
    },
change it as
"require": {
    "laravelcollective/html": "5.2.*"
},
Now go to command prompt and type
composer update
After this open the “app.php” file located in config folder e.g. D:\wamp\www\bitspedia\config add following things
Remember don’t delete any text while adding these classes
'providers' => [
    Collective\Html\HtmlServiceProvider::class,
],
'aliases' => [
     
'Form' => Collective\Html\FormFacade::class,
     
'Html' => Collective\Html\HtmlFacade::class,
 
],
Another thing you must do before starting a form is define its URL i.e. which URL will be hit to open this form, for that open routes.php file located in http folder which is located in app folder e.g. D:\wamp\www\bitspedia\app\Http
For now just define a function in “routes.php” which will just tell that when a specific URL is hit it must open the form. We will also create a function which tells what it will do when form is submitted, we just want to print “information received”.



Route::get('createUser',function(){
    return View::make('form');
});

Route::get('storeUser',function(){
    return
"information received";
});

This tells that when createUser is hit it must open the form located in views.
Last work you need to do is build a migration as explained in migration article, however let me show you the up and down methods of the migration you will build
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->string('name');
        $table->string('subjects');
        $table->string('gender');
        $table->date('date_of_birth');
        $table->integer('phone_no');
    });
}
public function down()
{
    Schema::drop("users");
}
Now you are ready to start your form

Creating a form
Now first of all you must know where to create form, as form is shown to user so it must be located in views folder located in resource folder e.g. D:\wamp\www\bitspedia\resources\views

Create a php file here named as form.blade.php
“form” is name of my form so you can change it however “blade” is extension. Blade is templating engine. If you don’t know what templating engine is don’t worry, you will know it after reading this.
Now let’s start writing your code in form.blade.php file. The output of the following code is shown below.

{{ Form::open(['url'=>'storeUser' , 'method'=>'post', 'files' => true]) }} //starting the form
{{Form::label('Name', 'Name',array('id'=>'namefield','class'=>'textfield', 'style'=>'height:100%'))}}<br> //label

{{Form::input('text', 'name','', array('id'=>'namefield'))}}<br><br>//textfiled

{{Form::label('OOP', 'OOP')}}<br>
{{ Form::checkbox('oop', true)}}
//checkbox
{{Form::label('DS', 'DS')}}
{{ Form::checkbox('ds')}}
{{Form::label('SC', 'SC')}}
{{ Form::checkbox('sc')}}<br><br>

{{Form::label('Gender', 'Gender')}}<br>//radio button
{{Form::label('Male', 'Male')}}
{{ Form::radio('gender', 'male')}}
{{Form::label('Female', 'Female')}}
{{ Form::radio('gender', 'female')}} <br><br>
{{Form::label('DateOfBirth', 'Date Of Birth')}}<br>//date type
{{Form::date('date')}}<br><br>
{{Form::label('PhoneNo', ' PhoneNo ')}}<br> //number type
{{Form::number('phone_no', 'value')}}<br><br>
{{Form::file('image')}}<br><br>
{{Form::select('size', array('English', 'Math'), 'Math')}} <br><br> //select with two options
{{Form::submit('enter')}} //button
{!! Form::close() !!} //close the form

The form starting line will generate the following code
<form method="POST" action="http://localhost/bitspedia/public/index.php/storeUser" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden">
You can see that 'url'=>'storeUser' tells us where to go when submit this form and 'files' => true tells us that this form contains some file to be uploaded and 'method'=>'post' tells us the method by which this form will be submitted
The first label in the form and the very next line i.e. text filed will generate the following code
<label for="Name" id="namefield" class="textfield" style="height:100%">Name</label><br>
<input id="namefield" name="name" type="text" value=""><br>
You see we are writing a simple code and it is automatically generating the php code for it, this is what a templating engines do.
So we have created a form with a text filed and label. The id of the label is “namefield” and
class of that is “textfield” and we have also used styling in it. I gave an empty single quotation marks in the text field that’s because the third attribute is equal to value so if you want to set id,class etc of the text field you have to give any value in the third attribute.
We created three chekboxes with “OOP” selected as default. It is done by giving it a 2nd argument as true.
We have created a drop down list with two options i.e. English and math and Math selected as default bu writing it in the third attribute.
And the last line where we are closing the form will simple generate
</form>


Migrations (Creating Project)

Creating a project
First of all open the command prompt and go to location where you want your project to be e.g. D:>\wamp\www
Then write the following line
composer create-project laravel/laravel bistpedia

bitspedia is name of my project, you can give any name.
Before we talk about migrations we need to set few things:

Go to .env file located in your project and change the following code as

DB_HOST=localhost

DB_DATABASE=bitspedia

DB_USERNAME=root

DB_PASSWORD=1234

Remember that bitspedia is name of my database, user name and password of mysql is root and 1234 respectively, change this code according to your setting.

Then open databse.php file located in config folder and change the following code as

'mysql' => [

    'driver'    => 'mysql',

    'host'      => env('DB_HOST', 'localhost'),

    'database'  => env('DB_DATABASE', 'bitspedia'),

    'username'  => env('DB_USERNAME', 'localhost'),

    'password'  => env('DB_PASSWORD', '1234'),

    'charset'   => 'utf8',

    'collation' => 'utf8_unicode_ci',

    'prefix'    => '',

    'strict'    => false,

],

Remember that I am using mysql so I changed in this and as mentioned above bitspedia is name of my database, user name and password of mysql is root and 1234 respectively change this code according to your settings.
MIGRATIONS
Migrations are just a php source file. Have you ever faced a problem of creating, deleting and specially updating a database, here is the solution. It creates deletes and updates database using php code, so that all team members have same database of their project. It contain two functions up() and down(). Up is used to make some change in database while down is used to remove or undo that change in database.
Now if you go to the migration folder located in database, you will see two files one named create_users_table and other named create_password_resets_table with time-stamped in there beginning, these are already created migrations so if you don’t need them you can just delete them. So we will delete them and create our own migration.
Let’s create a migration.
We will use an Artisan command line interface
. Write the following line in command prompt
php artisan make:migration create_users_table
This will make a php file in migrations folder named something like this 2016_01_21_203540_create_users_table, migrations are time-stamped so they are always executed in order.
Now open this file. You can see that it has created a class named CreateUsersTable
so class name is good it tells what the purpose of class is. You can see two functions in it up() and down(). As mentioned above the up() is used to make some change so let’s make first change in our database. We want to create a table named “users” with attributes id, name and email. And as mentioned above the down() is used to undo the change so in this case we just want our down function remove this table so we will update our up and down functions as following

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
    });
}
public function down()
{
    Schema::drop("users");
}
You can use a variety of column types when building your tables.
Just writing this will not do anything so we need to run these migrations, for that write the following line in your command prompt.
php artisan migrate
Now check you database you will see two tables and one of them is what you wanted to create i.e. users. If you check the structure of that table you can see that it contains three columns i.e. id, name and email. Remember that laravel keeps record of migrations so every time you run migrations it will only run new migrations and will not repeat any same migration again.

Now let’s make a change in our table and add a fatherName field in our users table. Remember that always use a new migration to alter your table. So we will create new migration
php artisan make:migration add_field_in_users_table

Then we will change its methods as following:

public function up()

{

    Schema::table('users', function ($table) {

        $table->string('fatherName');

    });

}

public function down()

{

    Schema::table('users', function ($table) {

        $table->dropColumn('fatherName');

    });

}
 
And then run this migration

php artisan migrate
If you have changed in your existing migration for some reason, you can use
php artisan migrate:refresh
This will first run the down() off all migrations and then run up() of all of them.
If you want to undo the last migration you can use
php artisan migrate:rollback
If you want to undo all the migrations you can use
php artisan migrate:reset