Skip to content
Advertisement

FormRequest message in laravel 8 not show messages

In my laravel 8 app I am trying to create two files CreateUserRequest and updateUserRequest to use personalized validations.

In the method rules I´m calling my model’s variable $createRules but when I send my form, this don´t send, don´t show messages, error… Nothing.

I have attached CreateUserRequest, my model and controller’s store method:

CreateUserRequest

namespace AppHttpRequests;

use IlluminateFoundationHttpFormRequest;
use AppModelsUser;

class CreateUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
    
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return User::$createRules;
    }
}

Model

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use SpatiePermissionTraitsHasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'surname',
        'experience',
        'skills',
        'education',
        'location',
        'profesion',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public static $createRules = [
        'name'       => 'required|string|max:191',
        'email'      => 'required|string|email|max:191|unique:users',
        'password'   => 'required|min:4|max:10|confirmed',
    ];

    public static $updateRules = [
        'name'  => 'required|string|max:191',
        'email' => 'required|string|email|max:191|unique:users',
    ];
}

Controller’s store method

namespace AppHttpControllersAdmin;

use AppHttpControllersController;
use AppHttpRequestsCreateUserRequest;
use AppHttpRequestsUpdateUserRequest;
use AppModelsRole;
use AppModelsUser;
use Flash;
use IlluminateHttpRequest;
use IlluminateSupportFacadesResponse;
use IlluminateSupportStr;
use InterventionImageImageManagerStatic as Image;
use JamesDordoyLaravelVueDatatableHttpResourcesDataTableCollectionResource;
use PrettusValidatorExceptionsValidatorException;

public function store(CreateUserRequest $request)
{
    try {
        $data = array(
            'name'      => $request->get('name'),
            'email'     => $request->get('email'),
            'password'  => password_hash($request->get('password'), PASSWORD_BCRYPT),
            'api_token' => Str::random(60),
        );

        $user = User::create($data);
        $roles = $request->get('roles');

        // We assign the Client's role
        if(empty($roles)) {
            $user->assignRole(2);
        } else {
            foreach($roles as $rol){
                $user->assignRole($rol);
            }
        }
    } catch (ValidatorException $e) {
        Flash::error($e->getMessage());
    }

    Flash::success('This is a message!');
    
    return redirect()->route('users.index');
}

In the blade I have @include('flash::message') for getting flashed messages, and this view it´s included in other @include('admin.layouts.alertMessage').

I don´t know what I am doing wrong.

Thanks for help me and sorry for my bad English.

UPDATED

my problem i think that i don´t arrive to my controller. I´m doin echo in my function with one exit and load all my page without message echo

attach my form and my routes:

<form action="{{ route('users.store') }}" method="POST">
    @csrf
    @include('admin.users.fields')
</form>

routes

/** USERS BLOQ ROUTES */
Route::resource('users', UserController::class);

Advertisement

Answer

TBH, i didn’t know that you can get validation logic from their Model. My advice is just copy paste your validation logic to the request. Since Request is only for Validation purpose ( CMIIW )

CreateRequest

public function rules()
    {
        return [
            'name'       => 'required|string|max:191',
            'email'      => 'required|string|email|max:191|unique:users',
            'password'   => 'required|min:4|max:10|confirmed',
        ];
    }

UpdateRequest

public function rules()
        {
            return [
                'name'  => 'required|string|max:191',
                'email' => 'required|string|email|max:191|unique:users',
            ];
        }

UPDATE

Just combine it to one Requests, give RequiredIf for password request, in case your update route contains update

use IlluminateValidationRule;
...

public function rules()
{
    return [
          'password' => Rule::requiredIf(str_contains(url()->current(), 'update')) . '|min:4|max:10|confirmed',
    ]
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement