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

Michael Fayez's avatar

why my post didn't saved in the database

Everything is going well but I can't find the post in the database How to save selected post 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 $post_id;
    public $project;

    public array $mediaToRemove = [];

    public array $listsForFields = [];

    public array $mediaCollections = [];

    public $selectedProjectId = null;
    
    public $selectedPostId = 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();
    }



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


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

    // Assign the selected project and post IDs to the design instance
    $this->design->project_id = $this->selectedProjectId;
    $this->design->post_id = $this->selectedPostId;
    $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
3 replies
LaryAI's avatar
Level 58

Based on the code snippet you've provided, it seems like you're using Laravel Livewire to create a form that saves a Design model to the database. The submit method is responsible for saving the Design instance after validation.

Here's a solution that ensures the Design instance is saved correctly:

  1. Make sure that the Design model has the fillable or guarded property properly set to allow mass assignment of the project_id and post_id attributes.

  2. Ensure that the submit method is being called when the form is submitted. You should have a Livewire action in your form like wire:submit.prevent="submit".

  3. Check that the validate method is not failing. If validation fails, the submit method will not proceed to save the model.

  4. Confirm that the selectedProjectId and selectedPostId are being set correctly when the form is submitted.

  5. Make sure that the database connection is configured correctly and that the designs table exists with the correct columns.

Here's an example of how you might adjust the Design model to allow mass assignment:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Design extends Model
{
    protected $fillable = ['project_id', 'post_id', 'team_id', 'note', 'statues', 'confirmation', 'review'];
    // OR
    protected $guarded = [];
    
    // ... rest of the model
}

And here's how you might adjust your form in the Livewire component's view:

<form wire:submit.prevent="submit">
    <!-- form fields -->
    <button type="submit">Save Design</button>
</form>

If you've checked all of the above and the issue persists, you might want to add some debugging code to the submit method to ensure that it's being called and that the Design instance has the expected values before calling save(). You can use dd() or Log::info() to output the current state of the Design instance.

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

    // Debugging: Dump the design instance to see if it has the correct values
    dd($this->design);

    // Assign the selected project and post IDs to the design instance
    $this->design->project_id = $this->selectedProjectId;
    $this->design->post_id = $this->selectedPostId;
    $this->design->save();
    $this->syncMedia();
    event(new DesignCreated($this->design));

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

By following these steps, you should be able to diagnose why the Design instance is not being saved to the database.

Snapey's avatar

probably because you encountered a validation error. Do you have method in the blade file to show errors?

gych's avatar

Do you mean by post not saving in the database, that post_id is empty ?

Is the project_id saved ?

Like @snapey already said, make sure that your validation passed.

Please or to participate in this conversation.