Home > database >  store() method does not perform the registration of a record in Laravel 9
store() method does not perform the registration of a record in Laravel 9

Time:09-07

When registering a record in my form from the file create_blade.php the page is redirected to the index.blade.php (which in this case is like '/'), but the record does not appear on this page where there is the existence of a table that lists the records.

  • create_blade.php

    <form action="{{ url("create") }}" method="POST">
          {{ csrf_field() }}
          ...
    </form>

  • web.php

    Route::controller(HunterController::class)->group(function () {
        Route::get('/', 'index');
        Route::get('/create', 'create');
        Route::get('/update/{id}', 'edit');
        Route::post('create', 'store');
        Route::patch('/update/{id}', 'update');
        Route::delete('/delete/{id}', 'destroy'); 
    });

  • HunterModel.php

    use HasFactory;
    protected $table = "hunter";
    protected $primaryKey = 'id';
    const CREATED_AT = 'date_register';
    const UPDATED_AT = 'date_update';
    protected $fillable = [
        'name_hunter',
        'year_hunter',
        'height_hunter',
        'weight_hunter',
        'type_hunter',
        'type_nen',
        'type_blood'
    ];

  • HunterController.php

    public function store(Request $request)
    {
        $validations = $request->validate(
        [
            'name_hunter' => 'required|max:50',
            'year_hunter' => 'required|numeric',
            'height_hunter' => 'required|numeric',
            'weight_hunter' => 'required|numeric',
            'type_hunter' => 'required|max:30',
            'type_nen' => 'required|max:30',
            'type_blood' => 'required|max:3',
        ]);
        HunterModel::saved($validations);
        return redirect()->to('/'); 
    }

CodePudding user response:

you confused ::saved() - event method that's fired when element is created/updated with ::create() method, that creates a record.

if you replace saved with create in HunterController::store, it will create a new record.

btw check out resource controllers, that's a lot more convenient way to create generic controllers like this.

  • Related