Search code examples
laravellaravelcollective

Laravel Collective - Model binding issue for non eloquent table names


I have a User model that has to have a table named admin_users, which is already stipulated in the model (protected $table = 'admin_users';)

I am using Laravel Collective form as follows:

{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'put']) !!}

My validation as follows:

  $rules = array(
        'first_name'    => 'required',
        'last_name'     => 'required',
        'email'         => 'email|max:255|unique:users',
        'country_id'    => 'required|numeric',
        'user_status'   => 'required'
    );

The only reason I am using Laravel Collective FORM::model for the ease of getting the request input back when validation fails:

(return redirect()->back()->withErrors($validator)->withInput($request->all())

On validation success though I am getting:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'crm.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = jocelyn33@example.com) The weird thing is that it's not taking the table from User class table.

My question is if there is a way to have FORM::model get admin_users table name rather than users, and if I decide to let go of FORM::model and use FORM::open, would I still be able to get back request inputs of a failed validation?


Solution

  • Your validation rules are defining what table to use for a unique check:

    'email'         => 'email|max:255|unique:users',
    

    unique:users is telling the unique rule to use the users table.

    unique:table,column,except,idColumn - Laravel Docs 5.6 - Validation - Unique Rule