MikasaAck's avatar

Data not stored in database but no error is showing

I am trying to store a new user based on its role, but the data is not store in database and no error is showing in terminal nor in console. So I cannot track where the error is coming from. When I submit data in the form, the page refreshes and nothing happens. Here is the model:


namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use ProtoneMedia\LaravelVerifyNewEmail\MustVerifyNewEmail;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Image\Manipulations;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class User extends Authenticatable implements MustVerifyEmail, HasMedia
{
  use HasApiTokens, HasFactory, Notifiable, HasRoles, MustVerifyNewEmail, InteractsWithMedia;

  protected array $guard_names = ['sanctum', 'web'];

  /**
   * The attributes that are mass assignable.
   *
   * @var array<int, string>
   */
  protected $fillable = [
      'name',
      'email',
      'password',
      'title',
      'email_verified_at',
      'phone',
      'post_code',
      'city',
      'country',
  ];

  /**
   * The attributes that should be hidden for serialization.
   *
   * @var array<int, string>
   */
  protected $hidden = [
      'password',
      'remember_token',
  ];

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


  public function registerMediaConversions(Media $media = null): void
  {
      $this
          ->addMediaConversion('preview')
          ->fit(Manipulations::FIT_CROP, 300, 300)
          ->nonQueued();
  }

  /**
   * Local scope to exclude auth user
   * @param $query
   * @return mixed
   */
  public function scopeWithoutAuthUser($query): mixed
  {
      return $query->where('id', '!=', auth()->id());
  }

  /**
   * Local scope to exclude super admin
   * @param $query
   * @return mixed
   */
  public function scopeWithoutSuperAdmin($query): mixed
  {
      return $query->where('id', '!=', 1);
  }


};

That's the controller:

public function store(StoreUserRequest $request)
    {
        dd($request->all());
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'title' => $request->input('title'),
            'password' => bcrypt($request->input('password')),
            'email_verified_at' => now(),
        ]);
    
        $user->assignRole([$request->input('role')]);
    
        return redirect()->route('users.index')->with('message', 'User created successfully');
    } 

and thats the migration file:

0 likes
16 replies
MikasaAck's avatar
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('title');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};
 

and this is the form:

<x-app-layout>
    <div>
        {{--Breadcrumb start--}}
        <div class="mb-6">
            {{--BreadCrumb--}}
            <x-breadcrumb :breadcrumb-items="$breadcrumbItems" :page-title="$pageTitle" />
        </div>
        {{--Breadcrumb end--}}

        {{--Create user form start--}}
        <form method="POST" action="{{ route('users.store') }}"  class="max-w-4xl m-auto">
            @csrf
            <div class="bg-white dark:bg-slate-800 rounded-md p-5 pb-6">

                <div class="grid sm:grid-cols-1 gap-x-8 gap-y-4">


                    {{--Name input end--}}
                    <div class="input-area">
                        <label for="name" class="form-label">{{ __('Name') }}</label>
                        <input name="name" type="text" id="name" class="form-control"
                               placeholder="{{ __('Enter your name') }}" value="{{ old('name') }}" required>
                        <x-input-error :messages="$errors->get('name')" class="mt-2"/>
                    </div>

                    {{--Email input start--}}
                    <div class="input-area">
                        <label for="email" class="form-label">{{ __('Email') }}</label>
                        <input name="email" type="email" id="email" class="form-control"
                               placeholder="{{ __('Enter your email') }}" value="{{ old('email') }}" required>
                        <x-input-error :messages="$errors->get('email')" class="mt-2"/>
                    </div>

                    {{--Email input start--}}
                    <div class="input-area">
                        <label for="password" class="form-label">{{ __('Password') }}</label>
                        <input name="password" type="password" id="password" class="form-control" placeholder="{{ __('Enter Password') }}" >
                        <x-input-error :messages="$errors->get('email')" class="mt-2"/>
                    </div>

                    {{--Password input end--}}
                    {{--Role input start--}}
                    <div class="input-area">
                        <label for="role" class="form-label">{{ __('Role') }}</label>
                        <select name="role" class="form-control">
                            <option value="" selected disabled>
                                {{ __('Select Role') }}
                            </option>
                            @foreach($roles as $role)
                                <option value="{{ $role->id }}">
                                    {{ $role->name }}
                                </option>
                            @endforeach
                        </select>
                        <iconify-icon class="absolute right-3 bottom-3 text-xl dark:text-white z-10"
                                      icon="material-symbols:keyboard-arrow-down-rounded"></iconify-icon>
                    </div>
                    {{--Role input end--}}
                    {{--Title input start--}}
                    <div class="input-area">
                        <label for="title" class="form-label">{{ __('Title') }}</label>
                        <select name="title" class="form-control">
                            <option value="Administrator" >
                            {{ __('Administrateur') }}
                            </option>
                            <option value="DG" >
                            {{ __('DG') }}
                            </option>
                            <option value="chargé de projets" >
                            {{ __('Chargé de projets') }}
                            </option>
                            <option value="commercial" >
                            {{ __('Commercial') }}
                            </option>
                            <option value="technique" >
                            {{ __('Technique') }}
                            </option>
                            <option value="financier" >
                            {{ __('Financier') }}
                            </option>
                          
                        </select>
                        {{--Title input end--}}
                        <iconify-icon class="absolute right-3 bottom-3 text-xl dark:text-white z-10"
                                      icon="material-symbols:keyboard-arrow-down-rounded"></iconify-icon>
                    </div>
                   
                </div>
                <button type="submit" class="btn inline-flex justify-center btn-dark mt-4 w-full">
                    {{ __('Save') }}
                </button>
            </div>

        </form>
        {{--Create user form end--}}
    </div>
</x-app-layout>

MikasaAck's avatar

@migsAV Here are the routes:

Route::resource('users', UserController::class);

MikasaAck's avatar

@migsAV Yes

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreUserRequest 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<string, mixed>
     */
    public function rules()
    {
        return [
            'name' => ['required', 'string', 'max:255',],
            'title' => ['required', 'string', 'max:255',],
            'email' => ['required', 'string', 'email:rfc,dns', 'max:255', 'unique:users',],
            'password' => ['required', 'string', 'min:8',],
            'role' => ['required', 'exists:roles,id'],
        ];
    }
}

migsAV's avatar

@mikasaack does any data get dumped when you do the dd($request->all()) in your controller?

migsAV's avatar

@MikasaAck that's very strange, can you try running this command php artisan route:list --name=users and see that you only have one users.store

migsAV's avatar

@MikasaAck can you also try changing the following

Try removing 'exists:roles,id' for the roles validation just to see if the data passes

Snapey's avatar

you dont have any way of displaying issues with role validation

MikasaAck's avatar

I think it's something related to the route, the action 'post' defined in the form is not executing. It just refreshes because the button has a type of submit...

MikasaAck's avatar

@krisi_gjika It doesn't reach the route, i've tried dd() nothing happens except that the page refreshes since the button is of type submit

Snapey's avatar
Snapey
Best Answer
Level 122

@MikasaAck whats it got to do with the button? It should be doing a submit, that is what is expected of it.

1st step, You never covered the role validation error. Your check of roles could be invalid and the form is returning with a role validation error, but you have no way to display the error so the page just appears to refresh.

Add somewhere on the page;

    @forelse($errors->all() as $whoops)
        {{ $whoops }}
    @empty
        NO ERRORS
    @endforelse

If this does not display anything, then try;

2nd step, open the browser network tools

refresh the form

clear the network log

press submit. What happens? What route is called? Is it a post request?

MikasaAck's avatar

@Snapey Thank you! I figured out the error, and it was related to the validation rules !! Thank you so much

jumbaeric's avatar

The form has got to be hitting the wrong route or the submit button is not bound to that form

Please or to participate in this conversation.