skip to Main Content

I’m developing a Laravel 11 application that asks users to submit data, which is then saved to a database. My migrations have successfully created the necessary tables, but I’m having an issue. I can’t seem to save data to the database. After submitting the form, there are no errors, but the database remains empty, and I am redirected to index.php as expected.

I’ve included parts of my code below for reference:

ProjectController.php

<?php

namespace AppHttpControllers;

use NetteSchemaValidationException;
use AppModelsproject;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

class ProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {  
        $projects = project::query()->orderBy('created_at', 'desc')->paginate(5);
        return view('project.index', ['project' => $projects]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('project.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        dd("Form submitted");
        try {
            $data = $request->validate([
                'title' => ['required', 'string'], 
                'university' => ['required', 'string'], 
                'category' => ['required', 'string'], 
                'description' => ['required', 'string'],
                'yesno' => ['required', 'string'], 
                'partner' => ['string'],
                'concept' => ['required', 'string'],
                'video' => ['required', 'string'],
            ]);
            $data['user_id'] = Auth::id();
            $project = project::create($data);
            return redirect()->route('project.index', $project)->with('success', 'Project created successfully!');
        
        } catch (ValidationException $e) {
            // Handle validation errors
            return back()->withErrors($e->validator)->withInput();
        }
    }
}

Project.php

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Project extends Model
{
    protected $fillable = [
        'title', 'university', 'category', 'description',
        'yesno', 'concept', 'video', 'partner', 'user_id'
    ];
}

create.blade.php

<x-app-layout>
    <x-slot name="dashboard">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    <form action="{{ route('project.store') }}" class="space-y-4 p-4 bg-gray-100 rounded shadow-md" method="POST">
                        @csrf
                        <!-- Project Title -->
                        <div class="flex items-center">
                            <label class="w-1/4 font-semibold text-black">Project Title:</label>
                            <input type="text" name="title" class="rounded border border-gray-300 p-2 w-full">
                        </div>
                        <!-- Other fields here... -->
                        
                        <!-- Submit Button -->
                        <div class="flex justify-end">
                            <input type="submit" name="sub" class="bg-blue-500 text-white rounded px-4 py-2 hover:bg-blue-600">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

CreateProjectsTable.php

<?php

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->string('title', 50);
            $table->string('university', 50);
            $table->string('category', 50);
            $table->longText('description');           
            $table->string('yesno', 5);
            $table->text('partner');
            $table->string('concept', 500);
            $table->string('video', 100); 
            $table->foreignId('user_id')->constrained('users');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('projects');
    }
};

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=student_showcase
DB_USERNAME=root
DB_PASSWORD=

Could you help me understand why data isn’t being saved to the database and why there are no error messages?

2

Answers


  1. If there are no errors here and you are being redirected to correct controller method, I guess it can be config cache issue. Try running:

    php artisan config:clear
    

    to remove config cache to make sure mysql connection is really used there

    Login or Signup to reply.
  2. Maybe try to make a model instance of Project in your project controller.

    <?php
    
    use AppModelsProject
    
    class ProjectController extends Controller
    {
        /**
         * Display a listing of the resource.
         */
        public function index()
        {  
            $projects = Project::all()
                   ->orderBy('created_at', 'desc')
                   ->paginate(5);
            return view('project.index', ['project' => $projects]);
        }
    
        /**
         * Show the form for creating a new resource.
         */
        public function create()
        {
            return view('project.create');
        }
    
        /**
         * Store a newly created resource in storage.
         */
        public function store(Request $request)
        {
           $validated = $request->validate([
            'title' => //your validation rules
            'other' => //more
            ]);
    
           try{
               $project = new Project();
               $project->title = $request->title
               //and the rest with this logic aswell
               $project->save();
              }catch (ValidationException $e) {
                // Handle validation errors
                return back()->withErrors($e->validator)->withInput();
            }
            
        }
    `
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search