Reputation: 3593
I made a crud for my users in backpack. When I create a user everything works fine but if I update I get an error for "Password" since if I dont want to update it I leave it blank and password cannot be null.
How can I not add "password" to the POST if I leave it blank? Or how do I default to the current password?? and also have a "confirm" field?
In UserCrudController.php
<?php
namespace App\Http\Controllers\Admin;
use Backpack\CRUD\app\Http\Controllers\CrudController;
use App\User;
use Auth;
// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\UserCrudRequest as StoreRequest;
use App\Http\Requests\UserCrudRequest as UpdateRequest;
class UserCrudController extends CrudController {
public function setup() {
$this->crud->setModel("App\User");
$this->crud->setRoute(config('backpack.base.route_prefix')."/user");
$this->crud->setEntityNameStrings('user', 'users');
$this->crud->setColumns([
['name' => 'lastname', 'label' => "Last Name"],
['name' => 'firstname', 'label' => "First Name"],
]);
$this->crud->addFields([
[
'name' => 'firstname',
'label' => "First name"
],
[
'name' => 'lastname',
'label' => "First name"
],
[ // Password
'name' => 'password',
'label' => 'Password',
'type' => 'password'
],
]);
}
public function store(StoreRequest $request)
{
// <--------- here is where a before_insert callback logic would be
$response = parent::storeCrud();
// <--------- here is where a after_insert callback logic would be
return $response;
}
public function update(UpdateRequest $request)
{
$user = User::find(Auth::user()->id);
// Hash password before save
if (!empty($request->password)) {
$request->offsetSet('password', Hash::make($request->password));
}else{
$request->offsetSet('password', $user->password );
}
return parent::updateCrud();
}
}
Error:
Integrity constraint violation: 1048 Column 'password' cannot be null (SQL: update `users` set `password` = , `updated_at` = 2017-10-06 15:08:25 where `id` = 1)
Upvotes: 2
Views: 5377
Reputation: 104
you can try remove password like this :
// Hash password before save
if (!empty($request->password)) {
$request->offsetSet('password', Hash::make($request->password));
}else{
$request->remove('password');
}
Upvotes: 0
Reputation: 3593
If anyone is making their own UserCrudController for Backpack look at their controller they did for a permissions manager:
Upvotes: 3