laravelrequiredfieldvalidator

Validate 'required' doesn't work for updating form in laravel6


I made a form for editing and updating username. The form is working correctly.

However, if make the username field empty and submit, validate function "required" doesn't go off and get the error:

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

I can't find why validation doesn't work. Here is my code.

UsernameController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\User;

class UsernameController extends Controller
{
    public function edit($id)
    {
        $data = User::findOrFail($id);
    return view('username.edit')->with('form',$data);
    }


    public function update(Request $request, $id)
    {

        $this->validate($request, ['name' => 'required']);
        $form = new User;
        $form = User::findOrFail($id);
        $form->name = $request->name;
        unset($form['_token']);
        $form->save();

        return redirect('/home/mypage')->with('status','Updated!');
    }
}

edit.blade.php

<form action="/username/{{$form->id}}" method="post">
@csrf
@method('PUT')
<input type="hidden" name="id" value="{{$form->id}}">

<p>Username<br>
<input type="text" name="name" value="{{$form->name}}"></p>

@error('name')
<p><span style="color:red;">{{$message}}</span></p>
@enderror

<p><input type="submit" value="Update"></p>

</form>

web.php

Route::resource('username','UsernameController',['only' => ['edit', 'update']]);

Solution

  • Try the following instead

    use use Illuminate\Support\Facades\Validator;
    //...
    $validator = Validator::make($request->all(), [
         'name' => 'required',
    ]);
    
    if ($validator->fails()) {
         return redirect()->back()
             ->withErrors($validator)
             ->withInput();
    }
    

    Edit

    You should, also, define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model.

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];