No One
No One

Reputation: 683

Laravel: Setting a Default Value for Blank/Null Input

This is the code in the migration:

$table->string('role')->default('Standard');

When I leave the input box blank, it gives me an error:

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role' cannot be null

How do we set the default value to "Standard" if the input box is left blank?

Code for Controller

 public function store(Request $request)
    {
        //return ['message' => 'I have your data'];
        $request->validate([
            'firstname' => 'required|string|max:191',
            'lastname' => 'required|string|max:191',
            'email' => 'required|string|email|max:191|unique:users',
            'password' => 'required|string|min:6',
        ]);
        return User::create([
        'firstname' => $request['firstname'],
        'lastname' => $request['lastname'],
        'email' => $request['email'],
        'phone' => $request['phone'],
        'role' => $request['role'],
        'usernotes' => $request['usernotes'],
        'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
        'created_by' => $request['created_by'],
        'updated_by' => $request['updated_by'],
    ]);
    }

Upvotes: 1

Views: 3244

Answers (2)

Akshay Khale
Akshay Khale

Reputation: 8361

In your code $request['role'] should be null which is causing the problem since the role field is not Nullable.

What you can do is, add the dwfault value if the role is null, just made following changes in your code and it should work.

public function store(Request $request)
{
    //return ['message' => 'I have your data'];
    $request->validate([
        'firstname' => 'required|string|max:191',
        'lastname' => 'required|string|max:191',
        'email' => 'required|string|email|max:191|unique:users',
        'password' => 'required|string|min:6',
    ]);
    return User::create([
    'firstname' => $request['firstname'],
    'lastname' => $request['lastname'],
    'email' => $request['email'],
    'phone' => $request['phone'],
    'role' => $request['role'] ?? 'Standard',
    'usernotes' => $request['usernotes'],
    'password' => Hash::make($request['password']), //make sure to import Hash: use Illuminate\Support\Facades\Hash;
    'created_by' => $request['created_by'],
    'updated_by' => $request['updated_by'],
]);
}

That should fix the issue.

Explanation: I am using Null coalescing (??) operator of PHP which will replace the null value with 'Standard'. It works only is PHP 7+, if you have a lower version of PHP then you can consider using the Ternary operator(?:).

Reference: https://www.php.net/manual/en/migration70.new-features.php

Upvotes: 2

PHP Geek
PHP Geek

Reputation: 4033

use nullable();

$table->string('role')->default('Standard')->nullable();

Upvotes: 1

Related Questions