What exactly is going on in the ->unique() function for Laravel migrations?

310 views Asked by At

In my create_users_table.php migration in my laravel set up there is the following line:

$table->string('email')->unique();

within the larger context of:

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

I understand that $table is an object of the class Blueprint, and that string is likely a method of that class because it takes parameters. What I don't understand is how a method of a class can have a method (string('email')->unique()??) as if it were an object. What is going on here?

1

There are 1 answers

0
Brett On BEST ANSWER

->unique() puts a unique index on the database column so 2 rows can't share the same email address.

If you attempt to save a second user with the same email it will result in a duplicate entry exception

If you are using Form Requests in laravel you can set a unique type and specify the table to look at - https://laravel.com/docs/5.5/validation#rule-unique

Oh and the reason you can tag on additional method calls ->string()->unique()->nullable() is because each method returns the original object.

EG

class my_object {
    public function string($name) {
        $this->name = $name;

        return $this;
    }
    public function other_method() { // do nothing }
}

$myObject = new my_object();
$myObject->string('sdfsdf')->other_method();