How to Create Model And Migration Using a Single Artisan Command

To generate a model and a migration file you need to run two separate commands.

Quick Tip : How to Create a Service Provider in Laravel 5.1

For model,

php artisan make:model Ticket

And For migration,

php artisan make:migration create_tickets_table --create=tickets

But, while going through Laravel documentation, I have found out that you can do both of these tasks in a single command.

You can use anyone of the following commands to generate both of these files at the same time.

php artisan make:model Ticket --migration

Or,

php artisan make:model Ticket -m

After executing anyone of the above commands we will get a,

Ticket.php (Model):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    //
}

And 2015_11_22_122910_create_tickets_table.php (Migration):

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTicketsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tickets', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tickets');
    }
}

In case you have any query, feel free to comment.

How to Create a Custom Service Provider in Laravel

In this short tutorial, we are going to create and register a custom service provider in Laravel.

Quick Tip : How to Determine if a View Exists in Laravel

First, open your command prompt, navigate to your project folder and run the following command.

php artisan make:provider DemoServiceProvider

This will generate a new file with name DemoServiceProvider.php located at app\Providers. Your service provider should look something like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class DemoServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

As you can see, all the service providers extends Laravel’s ServiceProvider class.

To register this provider navigate to config directory located in the root directory of your application and open app.php file. Now, we need to add our provider to the array of providers,

'providers' => [
    .
    .
    .
    App\Providers\DemoServiceProvider::class,
],

And that’s it. We have successfully created and registered a Laravel service provider.

How to Get Previous / Next Record in Laravel

In some situations, like while creating a previous and next navigation, you might want to get the ID of record next to your current record to create a Next button. And ID of your previous record to create the Previous button. You can easily perform this task by using the following code.

Quick Tip : Updating Column Types with Laravel Schema Builder

$user = User::find(5);

// Get ID of Previous User
$prevUser = User::where('id', '<', $user->id)->max('id');

// Get ID of Next User
$nextUser = User::where('id', '>', $user->id)->min('id');

Source : Stack Overflow

How to Change Column Types With Laravel Schema Builder

Sometimes you need to change the column type of an existing column in a your Laravel database. You can do this using migrations. In this example, we are going to change a address column in users table from VARCHAR to TEXT.

Quick Tip : Login Event Handling in Laravel 5

To do this, first we need to generate a migration file,

php artisan make:migration change_address_column_in_users_table --table=users

Now, you can use the following code in your newly created migration file to change column type of address from VARCHAR to TEXT.

public function up()
{
    DB::statement('ALTER TABLE users MODIFY COLUMN address TEXT');
}

public function down()
{
    DB::statement('ALTER TABLE users MODIFY COLUMN address VARCHAR(255)');
}   

 

Capture Last Login Time in Laravel 5

In this tutorial, we are going to capture the login time and date of the user and save it to database. To do this we are going to use Laravel handlers.

Useful Read : Set friendly names for validation attributes in Laravel 5

To save the date and time to the database, first we need to add a last_login column to the users table. To add the last_login column, create migration by using the following command.

php artisan make:migration add_last_login_column_to_users_table --table=users

This will generate a new migration file in the database\migrations folder.

Add the following line to your migration file.

$table->timestamp('last_login')->after('remember_token');

Now, type the following command to execute migration file.

php artisan migrate

This will create a new column within your users table.

Now generate a new event handler by using following command.

php artisan handler:event LoginEventhandler

This will create a new event handler within App/Handlers/Events.

Laravel Event Handler

Laravel Event Handler

As you can see, within the handle method we are using Carbon package to capture current date and time information.

Now, all we need to do is hook the event handler with login event.

To associate this handler with the login event navigate to App\Providers and open EventServiceProvider.php file and add the following code to $listen array.

'auth.login' => [
    'App\Handlers\Events\LoginEventHandler'
]

And that’s it. Now, when a user will login to his account the event handler will update last_login timestamp with correct value.

Set Nice Names For Validation Attributes in Laravel

Here’s a simple trick which allows you to change :attribute name ( e.g. first_name ) with a more proper and easy to read name ( e.g. First name ).

Quick Tip : Set Timezone in Laravel

To do this, we are going to use setAttributeNames method.

$nice_names = array(
    'first_name' => 'First Name'
);

$validator = Validator::make(Input::all(), $rules);
$validator->setAttributeNames($nice_names);

 

How to Set Timezone in Laravel 5

Here’s a quick tip which can be useful if you want to change the default timezone of your Laravel application.

Must Read : Renaming Database Tables in Laravel

To change timezone for your web application, navigate to config/app.php file and look for following code,

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

And replace UTC with your own timezone. For example you can change it to something like,

'timezone'  => 'Asia/Kolkata',

Additional Information : List of PHP Supported Timezones

Renaming Database Tables Using Laravel Migrations

In this post, we are going to rename an existing database table in Laravel 5. Let’s say you have a table called articles and you need to rename it to posts. So, here’s how you would do it.

See Also: How to Add New Column to Existing Table in Laravel

Open your terminal and run the following command.

php artisan make:migration rename_articles_table

This will generate a new PHP file inside your migrations folder (/database/migrations).  To rename the articles table we are going to use rename method.

class RenameArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('articles', 'posts');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::rename('posts', 'articles');
    }
}

As you can see, the rename method accepts two parameters, from i.e current name and to i.e new name.

Schema::rename($from, $to);

 

How to Add New Column to Existing Table in Laravel

Laravel comes with a built-in feature called Migrations for managing database. Migrations are nothing but a bunch of PHP files that are used to create or modify your database.

Useful Read: Helpers File in Laravel 5

In this tutorial, we are going to use migrations to add a new column to existing database in Laravel. In this example we are going to add a address column to users table.

First we need to create a new migration with artisan command.

php artisan make:migration add_address_column_to_users

Then, inside up method we are going use Schema Builder to add a new column.

public function up()
{
    Schema::table('users', function($table)
    {
        $table->string('address')->after('name');
    });
}

after is an optional feature which will allow you to add a new column after a specific column. If you are not using after your column will appear at the bottom of all columns.