Laravel provides unique validation rule for check unique value on a given database table.

Ref : https://laravel.com/docs/5.1/validation#rule-unique

Syntax

unique:table,column,except,idColumn,whereColumn1,whereValue1,whereColumn2,whereValue2,...

Ex1. Validate unique value in given database table

'username' => 'unique:users,username'

Ex2. Validate unique value except given ID

In mostly used when update existing record.

'username' => 'unique:users,username,'.$user->id

Ex3. Gives id column name if primary key of table isn't 'id'.

'username' => 'unique:users,username,'.$user->id.',user_id'

Ex4. Adding additional where clauses for more complex condition

If company has tag list and want to check unique value,

'name' => 'unique:tags,name,NULL,id,company_id,'.$company_id

If company has hierarchical folder list and want to check unique value per each node,

'name' => 'unique:folders,name,NULL,id,company_id,'.$company_id.',parent_id,'.$parent_id

To create migration, we can use this artisan command.

$ php artisan make:migration create_companies_table

Laravel will create a new migration file in database/migrations directory.

Generated file is like this:

<?php

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

class CreateCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

up() method is used to create a new tables or add new columns to table.
down() method is used to rollback.

We can use --create option when create migration to automatically generate base code.

$ php artisan make:migration create_companies_table --create=companies

Generated file is like this:

<?php

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

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

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

When insert a new row to pivot table, we can use attach() method like this:

$company = Company::find(1);
$company->users()->attach(1);

But this will not update created_at and updated_at timestamps column in pivot table.

To update timestamps, use withTimestamps() method on the relationship method.

class Company extends Model
{
  public function users()
  {
    return $this->belongsToMany(User::class)->withTimestamps();
  }
}

Error 1

Maximum call stack size exceeded error

Solution

Update npm using sudo npm i npm -g command.

Error 2

ENOENT: no such file or directory, scandir '/home/vagrant/app-name/node_modules/node-sass/vendor' error

Solution

Execute npm rebuild node-sass --no-bin-links command. (Reference)

I got the problem when using bican/roles Role module in my Laravel project.

There is an error when I check permission.

So I decided to move zizaco/entrust and tested all features working normal.

How to install Entrust

Install use composer

$ composer require zizaco/entrust:5.2.x-dev

Setting to config/app.php

Add bellow line to providers array in config/app.php.

    Zizaco\Entrust\EntrustServiceProvider::class,

Add bellow line to aliases array in config/app.php.

    'Entrust' => Zizaco\Entrust\EntrustFacade::class,

Setting to app/Http/Kernal.php

Add bellow lines to routeMiddleware array in app/Http/Kernal.php.

    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
    'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
    'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

Publish entrust.php file

$ php artisan vendor:publish

Database Setup

Generate Entrust migration

$ php artisan entrust:migration

It will generate the <timestamp>_entrust_setup_tables.php migration.

Execute migration

$ php artisan migrate

Trouble shootings

Error when execute migration

After create <timestamp>_entrust_setup_tables.php, you have to write your users table in this file. Open <timestamp>_entrust_setup_tables.php file and write name of users table to 28 line.

    $table->foreign('user_id')->references('id')->on('users')
        ->onUpdate('cascade')->onDelete('cascade');

This cache store does not support tagging

Set CACHE_DRIVER=array in .env file.

Error when delete role

In Laravel 5.2, error is occured when delete role. Because Entrust get User class using Config::get('auth.model').

EntrustRoleTrait.php file

    /**
     * Many-to-Many relations with the user model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users()
    {
        return $this->belongsToMany(Config::get('auth.model'), Config::get('entrust.role_user_table'),Config::get('entrust.role_foreign_key'),Config::get('entrust.user_foreign_key'));
       // return $this->belongsToMany(Config::get('auth.model'), Config::get('entrust.role_user_table'));
    }

So We have to return right user model by that position. There are two solutions for this.

1. Change EntrustRoleTrait.php file to use correct configuration value.

We can change Config::get('auth.model') to Config::get('auth.providers.users.model'). Laravel 5.2 already have users model information in that position.

2. Add auth.model value to config/auth.php file

We can also add new value to config/auth.php file to allow Entrust get rights value.

return [
  ...

  /**
   * Add this configuration for Entrust
   */
  'model' => App\User::class,
];

If you got bellow error when use memcached in Laravel, please check following steps.

exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Memcached' not found' in /var/www/gw/vendor/laravel/framework/src/Illuminate/Cache/MemcachedConnector.php:51

Install memcached

$ sudo apt-get install php5-memcached memcached

Enabled php5-memcached

sudo php5enmod memcached

Restart apache web server

$ sudo service apache2 restart

Check memcached service status

$ sudo service memcached status
* memcached is running

Clear cache

$ php artisan cache:clear

When I run composer update command in shell, composer displays warning like bellow.

You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug

And takes too long time to process.

I already go to https://getcomposer.org/xdebug reference and tried to disable xdebug option in php.ini file. But I couldn't found it.

This is the real reference to disable xdebug option in php.ini file.

Get what php.ini file is used

First, check what kind of php.ini file is used.

php -i | grep "php.ini"

Comment xdebug option

Search zend_extension option and comment it using ';(semicolon)'.

;zend_extension = "/path/to/my/xdebug.so"

If you can't find this option in php.ini file, maybe it is in conf.d folder. File name is like '20-xdebug.ini'. Open this file and comment it.

References

Clone laravel source to server

$ git clone https://github.com/zemna/groupware.git

Install necessary modules

$ npm install

$ composer install --no-dev -o --prefer-dist

$ bower install

Make .env

$ cp .env.example .env

Generate key to .env

$ php artisan key:generate

Execute gulp if necessary

$ gulp --production

Migrate database

$ php artisan migrate

Give owner to web server

$ chown -R www-data:www-data *

Set write permission

$ chmod -R 775 bootstrap/cache
$ chmod -R 775 storage

When I setup Laravel project for my company, I've faced the problem about SQL Server database connection problem. I've googled and now I can use it.

1. Install php7.0-sybase to Homestead

New version of Homestead uses php7.0 to serve laravel website. So, I installed php7.0-sybase using bellow command.

$ sudo apt-get install php7.0-sybase

2. Edit /etc/freetds/freetds.conf file

I don't know about TDS but I followed reference bellow,

$ sudo vi /etc/freetds/freetds.conf
[global]
    tds version = 7.2
    client charset = UTF-8

Also create /etc/freetds/locales.conf file to allow correct parsing of dates.

$ sudo vi /etc/freetds/locales.conf
[default]
    date format = %Y-%m-%d %I:%M:%S.%z

3. add getDateFormat() function to each Model classes

Eventhough I already set the datetime format from above, I still got the Data missing error when access Carbon class.
This is because the difference of datetime string format. My SQL Server gives '2016-06-20 13:00:00' datetime string to Laravel, but Carbon accepts 'Y-m-d H:i:s.000' format to create instance.

So, add getDateFormat() function to each Model classes to give format information.

protected function getDateFormat() {
  return 'Y-m-d H:i:s+';
}

SqlServerGrammer.php file returns Y-m-d H:i:s.000 DateFormat. Change it to Y-m-d H:i:s to apply all models or just delete this function. Because Grammer.php abstract class returns Y-m-d H:i:s format...

Laravel is the best PHP framework for develop web application.

Official Links

Video Tutorials

Copyright zemna. All right reserved.