Web progamming and database development

Diary of problems and solutions related to web programming, database development and related technologies and platforms.

Wordpress resolving add theme problem - Are you sure you want to do this?

If you are receiving the question "Are you sure you want to do this?" when you try to add theme, then make the necessary changes to php.ini
; Maximum size of POST data that PHP will accept.
post_max_size = 10M
; Maximum allowed size for uploaded files.
upload_max_filesize = 10M
to a value larger than your theme file.


Some tips and tricks in Laravel

1. Generating migration code with additional features

If you want to create migration code with additional functionality (codes for auto incrementing ids, timestamps which includes updated_at and created_at columns automatically. Plus it also adds drop statement for dropping the table in down() function), then use the following lines of code in your command prompt.

C:\wamp\www\laravelproject> php artisan migrate:make create_users_table --create=users

Here we have added extra code --create=users

This will create up() function like this

public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
});
}

Now you can add your choice of columns to it. Here I added two extra columns for unique email and for password

public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('password',60);
$table->timestamps();
});
}

2. If you want to alter one of the columns in the table.

Let's say we want to add a column called "permission" to the table users.

C:\wamp\www\laravelproject> php artisan migrate:make add_permission_column_to_users_table 

Add the following code to the up() and down() functions

public function up()
{
Schema::table('users', function($table){
$table->integer('permission');
});

}

public function down()
{
Schema::table('users', function($table){
$table->dropColumn('permission');
});
}

and run the migration code as

C:\wamp\www\laravelproject> php artisan migrate

3. If you face problems while running migration like

[PDOException]
SQLSTATE[HY000] [1045] Acc refus..............

In this case, it might be an environment issue.

To solve this run the code like this (if you are working on development environment):

C:\wamp\www\laravelproject> php artisan migrate --env=development

If you are working on production environment, then run like this:

C:\wamp\www\laravelproject> php artisan migrate --env=production

4. If you want to drop all the migration and re-run them, then

C:\wamp\www\laravelproject> php artisan migrate:refresh

5. If the mysql error is being displayed in French language, and you want it to be displayed in English.

Then run the following command going to the following directory

C:\wamp\bin\mysql\mysql5.6.17\bin>mysqld --lc_message=en_US

6. If you have problem in refreshing database migration and if you are receiving the errors like "pdoexception sqlstate 42s02 base table or view not found 1146"

In this case, drop the database and recreate the database and run the migration. It will help you migrate the tables successfully.

7. If you are getting error like "PDOException (1045)
SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)"

Go to app > config > local > database.php

There you will see the database homestead which you need to change. I have changed the settings like this and removed the configuration for pgsql (postGreSQL) because I am using MySQL.

'connections' => array(

'mysql' => array(
'driver'    => 'mysql',
'host'      => 'localhost',
'database'  => 'laravelproject',
'username'  => 'root',
'password'  => '',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
),

),

8. To access the list of artisan, use this command

C:\wamp\www\laravelproject> php artisan

9. If you find class doesn't exist error (even if the class is present in your controller), then run this command to auto load the classes

C:\wamp\www\laravelproject> php artisan dump-autoload

10. Displaying all sql statements in Eloquent

Plus the following code in routes.php and you will be able to see SQL statements Eloquent is executing. This will help you in better debugging

// Display all SQL executed in Eloquent Event::listen('illuminate.query', function($query) { var_dump($query); });

OR

DB::getQueryLog()

11. Displaying current laravel version
C:\wamp\www\laravelproject> php artisan --version

12. Displaying list of available commands
C:\wamp\www\laravelproject> php artisan list


Managing settings to debug in Laravel

1. You need to identify your host name first. To know the host name type the following on command mode.

C:\> hostname
SOM013

You will use this host name for setting up for proper debugging in step no 2.

2. Go to bootstrap > start.php and go to the position having following code.

$env = $app->detectEnvironment(array(
'local' => array('homestead'),
));

Change the above code to the following like this:

$env = $app->detectEnvironment(array(
'local' => array('homestead', 'SOM013'),
));

Here we have added the host name inside the array.

This will show you the stack trace with all the environment variables which helps in debugging. Enjoy debugging using Laravel!


Things to do for setting up Laravel Project

1. Creating a unique Laravel Key for the application or project.

Go to laravelproject > app > config > app.php

Change

key = 'YourSecretKeyGoesHere!'

to

key =''

Save the file and go to command line prompt

C:\wamp\www\laravelproject>php artisan key:generate

2. Configure database settings.

Go to app > config > database.php

Change the details like this. I changed the database name and username as they were not matching according to my database set up.

'mysql' => array(
'driver'    => 'mysql',
'host'      => 'localhost',
'database'  => 'laravelproject',
'username'  => 'root',
'password'  => '',
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix'    => '',
),

3. Install and create migration  table

C:\wamp\www\laravelproject>php artisan migrate:install 

Open localhost:phpmydmin and laravelproject databaes. There you will see migrations table created.

4. Creating authors table

C:\wamp\www\laravelproject>php artisan migrate:make create_authors_table

It creates migration file. For this go to app > database > migrations > ......................create_authors_table.php. Open this file.

There you will see CreateAuthorsTable class having up() and down() functions. Up() functions helps to make changes to the database while down() function helps to revert (perfom undo) operations for the changes made at up() function.

Define the up and down functions like this:

public function up()
{
Schema::create('authors', function($table){
$table->increments('id');
$table->string('name');
$table->text('biography');
$table->timestamps();
});
}

public function down()
{
Schema::drop('authors');
}

Execute/run this file via command mode as:

C:\wamp\www\laravelproject>php artisan migrate
Do you really want to run this command? yes

This will create an authors table in the database

Inserting records to the table. Create a class which helps to do that:

C:\wamp\www\laravelproject>php artisan migrate:make add_authors

Open add_authors.php file just created inside migration folder.

Add the following code to add the records:

public function up()
{
DB::table('authors')->insert(array(
'name' => 'Suresh Raj Bhattarai',
'biography' => 'Suresh is a good author',
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
));

DB::table('authors')->insert(array(
'name'=>'Surendra Sedhai',
'biography' => 'Surendra is a good author',
'created_at' => date('Y-m-d H:m:s'),
'updated_at' => date('Y-m-d H:m:s')
));
}

public function down()
{
DB::table('authors')->where('name', '=', 'Suresh Raj Bhattarai')->delete();
DB::table('authors')->where('name', '=', 'Surendra Sedhai')->delete();
}

Make changes to the table ie add the records by running this again:
C:\wamp\www\laravelproject>php artisan migrate

Look at the table authors. You will see two records added there.

If you want to undo the insertion, the run the rollback command like this:
C:\wamp\www\laravelproject>php artisan migrate:rollback

This rollbacks the last migration done to the database. That is it rollbacks the insertion of the data that took place to the authors table.

To rollback the creation of authors table, run the rollback command again.
C:\wamp\www\laravelproject>php artisan migrate:rollback
This will delete the table authoers.

To migrate everything back, then run the migration command like this
C:\wamp\www\laravelproject>php artisan migrate
This will create authors table and insert the values to the table again.

5. Go to app | views | hello.php

Clear the content inside body tag and type any html content you like. This will change the content of the laravel project for the index page.

Try browsing the page : http://localhost:81/laravelproject/public/

The reason behind displaying this view as hello.php is because of definition on routes file which is located at app > routes.php which has been defined like this way:

Route::get('/', function()
{
return View::make('hello');
});

Another example, if you create about.php inside the same view folder, then you can define routes like this way to open the file:

Route::get('/about', function(){
return View::make('about');
});

Browse the page as :http://localhost:81/laravelproject/public/about



Running Laravel project using Local Server Routes

Alternative 1:

Go to laravel project. Lets say
C:/>cd wamp/www/laravelproject

Type the following command to run the laravel project using local server routes
C:/wamp/www/laravelproject>php -S localhost:8888 -t public

Open a brower and enter the following URL on address bar
http://localhost:8888

Alternative 2:

To start the project at localhost:8000, run the following lines of command
C:/wamp/www/laravelproject>php artisan serve




Generating CRUD based on Doctrine Entity using Symfony2

In MySql database 

Initially make sure you have your database created on the mysql.

Create a table product on that database and create the fields for the product table.

In Git Bash

We assume that you are in your project root directory

Run the following command to create crud controller

php app/console generate:doctrine:crud

This will help you list the records, add records, edit records and delete records.

Entity shortcut name: AcmeDemoBundle:Product
If you want to create write action (means if you want to create/edit/delete record), then you have enter yes
Configuration format: yml
Routes prefix [/product] : Press Enter to give the routing prefix as it is.
Do you confirm generation: Press Enter to confirm.
Confirm automatic update of routing? Press Enter to confirm.

This will create CRUD controller.

Once a controller is created, if you want to overwrite any of the things to the existing controller, then run the following command.

php app/console generate:doctrine:crud --overwrite



Creating and removing Doctrine Entity using Symfony2 (Creating CRUD Application)

Creating Doctrine Entity

Open up the command line Git Bash

Go to the project folder
$ cd C:/wamp/www/Symfony2Project

Run the following command to create doctrine entity
php app/console generate:doctrine:entity

This entity helps to create class properties, getters and setters functions.

Entity shortcut name: AcmeDemoBundle:Product
Configuration format: yml

New field name: title
Field type (string): Enter
Field length [255]:100

New field name: price
Field type (string): float

New field name: (If you do not want to add extra field names, then press Enter)
Do you want to generate an empty repository class [no]? Enter
Do you want to confirm generation [yes]? Enter 

Removing Entity

- Delete Product.php file inside src/Acme/DemoBundle/Entity folders
- Delete Product.orm.yml file inside src/Acme/DemoBundle/Resources/config/doctrine folders

Reference: http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_entity.html


Creating and deleting bundle using Symfony2

Creating Bundle

Open up the command line Git Bash

Go to the project folder
$ cd C:/wamp/www/Symfony2Project

Run the generate bundle command
$php app/console generate:bundle

Bundle namespace: Suresh/Bundle/CrudBundle
Press Enter to confirm namespace
Press Enter again to confirm the target directory src.
Configuration format: yml
Generate the whole directory structure? yes
Do you confirm generation? Press enter to confirm.
Update kernel? Press enter for yes
Update routing? Press enter for yes

Now the bundle has been created and code has generated. This will also create a DefaultController.php inside Controller.

Running web server
$ php app/console server:run

To access the page, see the routing.yml inside Suresh/Bundle/CrudBundle/Resources/config folders. You will see the routing style as /hello/{name}

Open a browser and run the page like this way:

http://localhost:8000/hello/John

Deleting Bundle

To delete bundle, follow these steps
- Delete the folder "Suresh" located inside src folder.
- Open AppKernel.php located inside app folder. Inside registerBundles() function delete the following line.
new Suresh\Bundle\CrudBundle\SureshCrudBundle(),
- Open routing.yml located inside app/config and delete the following lines.
suresh_crud:
    resource: "@SureshCrudBundle/Resources/config/routing.yml"
    prefix:   /

This will help you deleting the bundle completely.