Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Michael Fayez's avatar

Why save is not working

why submit is not working, try to submit,, it submitted but not save the data in the database ...

<?php

namespace App\Http\Livewire\Design;

use App\Models\Design;
use App\Models\Post;
use App\Models\Project;
use App\Models\Team;
use Livewire\Component;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use App\Listeners\Design\DesignCreatedEmail;
use App\Events\Design\DesignCreated;

class Create extends Component
{
    public Design $design;

    public $posts;
    public $projects;
    public $post;
    public $project;

    public array $mediaToRemove = [];

    public array $listsForFields = [];

    public array $mediaCollections = [];

    public $selectedProjectId = null;

    public function addMedia($media): void
    {
        $this->mediaCollections[$media['collection_name']][] = $media;
    }

    public function removeMedia($media): void
    {
        $collection = collect($this->mediaCollections[$media['collection_name']]);

        $this->mediaCollections[$media['collection_name']] = $collection->reject(fn ($item) => $item['uuid'] === $media['uuid'])->toArray();

        $this->mediaToRemove[] = $media['uuid'];
    }

    protected function syncMedia(): void
    {
        collect($this->mediaCollections)->flatten(1)
            ->each(fn ($item) => Media::where('uuid', $item['uuid'])
                ->update(['model_id' => $this->design->id]));

        Media::whereIn('uuid', $this->mediaToRemove)->delete();
    }

    public function mount(Design $design)
    {
        $this->design = $design;
        $this->projects = Project::all(); // Load all projects
        $this->posts = collect();
        $this->initListsForFields();
    }

    public function updatedSelectedProjectId($projectId)
    {
        $this->posts = Post::where('project_id', $projectId)->get(); // Update posts based on selected project
    }



    public function render()
    {
        return view('livewire.design.create');
    }

    public function submit()
    {
        $this->validate();

        $this->design->save();
        $this->syncMedia();
        event(new DesignCreated($this->design));

        return redirect()->route('admin.designs.index');
    }

    protected function rules(): array
    {
        return [
            'design.project_id' => [
                'integer',
                'exists:projects,id',
                'nullable',
            ],
            'design.post_id' => [
                'integer',
                'exists:posts,id',
                'nullable',
            ],
            'mediaCollections.design_design' => [
                'array',
                'required',
            ],
            'mediaCollections.design_design.*.id' => [
                'integer',
                'exists:media,id',
            ],
            'design.statues' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['statues'])),
            ],
            'design.confirmation' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['confirmation'])),
            ],
            'design.note' => [
                'string',
                'nullable',
            ],
            'design.review' => [
                'nullable',
                'in:' . implode(',', array_keys($this->listsForFields['review'])),
            ],
            'design.team_id' => [
                'integer',
                'exists:teams,id',
                'required',
            ],
        ];
    }

    protected function initListsForFields(): void
    {
        $this->listsForFields['project']      = Project::pluck('name', 'id')->toArray();
        $this->listsForFields['post']         = Post::pluck('title', 'id')->toArray();
        $this->listsForFields['statues']      = $this->design::STATUES_RADIO;
        $this->listsForFields['confirmation'] = $this->design::CONFIRMATION_RADIO;
        $this->listsForFields['review']       = $this->design::REVIEW_RADIO;
        $this->listsForFields['team']         = Team::pluck('name', 'id')->toArray();
    }
}
0 likes
2 replies
LaryAI's avatar
Level 58

Based on the code snippet you've provided, there are a few potential reasons why the submit method might not be saving data to the database. Here are some steps to troubleshoot and resolve the issue:

  1. Validation Errors: Ensure that the validation rules are passing. If there's a validation error, the $this->design->save(); line won't be executed. You can debug this by adding a dd() or dump() statement before the save() method to see if there are any validation errors.

  2. Fillable/Guarded Attributes: Make sure that the Design model has the correct fillable or guarded attributes set. If the attributes you're trying to save are not fillable, they won't be saved to the database.

  3. Database Connection: Confirm that your database connection is configured correctly in your .env file and that the database server is running.

  4. Database Migrations: Ensure that the database tables and columns exist and match the attributes you're trying to save.

  5. Event Listeners: Since you're firing an event event(new DesignCreated($this->design)); after saving, make sure that there are no listeners that might be causing a rollback or any other database transaction issues.

  6. Error Handling: Add error handling to catch any exceptions that might be thrown during the save operation.

Here's an example of how you might modify the submit method to include some of these troubleshooting steps:

public function submit()
{
    $this->validate();

    try {
        $this->design->save();
        $this->syncMedia();
        event(new DesignCreated($this->design));

        session()->flash('message', 'Design saved successfully.');
        return redirect()->route('admin.designs.index');
    } catch (\Exception $e) {
        // Handle the exception and show an error message
        session()->flash('error', 'Failed to save design: ' . $e->getMessage());
        return redirect()->back()->withInput();
    }
}

Remember to replace the session()->flash() calls with the appropriate session handling for your Livewire component if needed.

If you've gone through these steps and the issue persists, you may need to provide more context or error messages for further assistance.

Snapey's avatar

You need to narrow down the issue rather than expect us to trawl through all this code

Please or to participate in this conversation.