Home > Software engineering >  Laravel: module is not stored to the database
Laravel: module is not stored to the database

Time:10-13

When I try to upload something to the database using the create method, this is not stored in the database. It looks like the page just refreshes. I am quite new to Laravel so any help would be appreciated.

Below I provided respectively the top of my blade view, my route and my controller. Is someone able to help me? I've searched in many other topics but couldn't find the solution to my problem.

@extends('layouts.app')

@section('content')
<div class="container">
    <form action="/module" enctype="multipart/form-data" method="POST">

        @csrf
        

        <div class="row">
            <div class="col-8 offset-2">
                <div class="row"><h3>Add New Module</h3></div>

                <div class="form-group row">
                    <label for="title" class="col-md-4 col-form-label">Module Title</label>


                    <input id="title"
                           type="text"
                           class="form-control @error('title') is-invalid @enderror"
                           name="title"
                           value="{{ old('title') }}"
                           autocomplete="title" autofocus>

                    @error('title')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror

                </div>

                <div class="form-group row">
                    <label for="category" class="col-md-4 col-form-label">Category</label>


                     <select id="category" onchange="getCategories()" class=" mt-1 block w-full py-2 px-3 border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm p-1.5 px-3 border-2  @error('category') border-red-500 @enderror">
                        <option disabled selected value> -- Kies één van de opties -- </option>
                        <option value="Schil">Schil</option>
                        <option value="Afbouw">Afbouw</option>
                        <option value="Installatie">Installatie</option>
                        <option value="Afwerking">Afwerking</option>
                    </select>

                    @error('category')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror

                </div>

Route:

    Route::get('/', function () {
    return view('welcome');
    });
    
    Auth::routes();
    
    Route::get('/module/create', 'App\Http\Controllers\ModulesController@create');
    Route::post('/module', 'App\Http\Controllers\ModulesController@store');

Controller:

class ModulesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function create()
    {
        return view('modules/create');
    }

    public function store()
    {
        $data = request()->validate([
            'title' => ['required', 'string', 'max:50'],
            'description' => ['required', 'string', 'max:255'],
            'price' => ['required', 'string'],
            'category' => ['required', 'string'],
            'subcategory' => ['required', 'string'],
            'image' => ['required', 'image'],
        ]);



        auth()->user()->modules()->create($data);


        
    }
}

CodePudding user response:

I think you don't need @method('post') just remove it. and better to named the post route to Route::post('/module', [App\Http\Controllers\ModulesController::class, 'store')->name('module.store'); then action={{ route('module.store') }} and should you have <button type="submit" class="btn btn-primary">Save</button> before </form> closing tag

CodePudding user response:

Problem 1

You mention "It looks like the page just refreshes" - this sounds like what might happen when there is a validation problem, right? Checking your code, I don't see anywhere that would display the validation errors. So maybe validation is failing, Laravel is bouncing you back to the form to tell you there is a validation error - but those errors are not displayed, so it looks like you just refreshed the page! This matches exactly what you describe.

How to display validation errors is described clearly in the docs. Include this code somewhere on your form page:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Problem 2

Because of the first problem, you haven't hit this one yet, but once it is fixed you will. Once your new model has been create()-d, nothing at all happens in the current code. This means you'll see a white/blank page in the browser after you submit the form, which is not a great user experience. So what do you want to do? Often redirecting to some kind of index list of the thing you just created is the way to go. For eg, maybe you'd like a page listing all the current user's modules. Convention would be to have that at /modules, so at the end of your store() method you could have something like:

return redirect('/modules');

Note this is just an example and won't actually work until you:

  • add a route for that URL;
  • add the corresponding controller method which generates the list;
  • add a view to display that list;
  • Related