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

Michael Fayez's avatar

the post doesn't saved in the database what's missing

I've tired for many days didn't know why the post didn't save in the database :- Here is the create component :-

<?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 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->design->post_id;
    $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();
    }
}

Here is the view :-

<form wire:submit.prevent="submit" class="pt-3">

    <div class="form-group {{ $errors->has('design.project_id') ? 'invalid' : '' }}">
        <label class="form-label" for="project">{{ trans('cruds.design.fields.project') }}</label>
            <select wire:model="selectedProjectId" name="project"
                class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
                required>
            <option value="">-- choose project --</option>
            @foreach ($projects as $project)
                <option value="{{ $project->id }}">{{ $project->name }}</option>
            @endforeach
        </select>
        <div class="validation-message">
            {{ $errors->first('design.project_id') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.project_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('design.post_id') ? 'invalid' : '' }}">
        <label class="form-label" for="post">{{ trans('cruds.design.fields.post') }}</label>

            <select wire:model="design.post_id" name="post"
                    class="mt-2 text-sm sm:text-base pl-2 pr-4 rounded-lg border
                    border-gray-400 w-full py-2 focus:outline-none
                    focus:border-blue-400" required>
            @foreach ($posts as $post)
                <option value="{{ $post->id }}">{{ $post->title }}</option>
            @endforeach
            </select>
        <div class="validation-message">
            {{ $errors->first('design.post_id') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.post_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('mediaCollections.design_design') ? 'invalid' : '' }}">
        <label class="form-label required" for="design">{{ trans('cruds.design.fields.design') }}</label>
        <x-dropzone id="design" name="design" action="{{ route('admin.designs.storeMedia') }}" collection-name="design_design" max-file-size="5" max-width="1200" max-height="630" />
        <div class="validation-message">
            {{ $errors->first('mediaCollections.design_design') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.design_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('design.statues') ? 'invalid' : '' }}">
        <label class="form-label">{{ trans('cruds.design.fields.statues') }}</label>
        @foreach($this->listsForFields['statues'] as $key => $value)
            <label class="radio-label"><input type="radio" name="statues" wire:model="design.statues" value="{{ $key }}">{{ $value }}</label>
        @endforeach
        <div class="validation-message">
            {{ $errors->first('design.statues') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.statues_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('design.confirmation') ? 'invalid' : '' }}">
        <label class="form-label">{{ trans('cruds.design.fields.confirmation') }}</label>
        @foreach($this->listsForFields['confirmation'] as $key => $value)
            <label class="radio-label"><input type="radio" name="confirmation" wire:model="design.confirmation" value="{{ $key }}">{{ $value }}</label>
        @endforeach
        <div class="validation-message">
            {{ $errors->first('design.confirmation') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.confirmation_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('design.note') ? 'invalid' : '' }}">
        <label class="form-label" for="note">{{ trans('cruds.design.fields.note') }}</label>
        <input class="form-control" type="text" name="note" id="note" wire:model.defer="design.note">
        <div class="validation-message">
            {{ $errors->first('design.note') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.note_helper') }}
        </div>
    </div>
    <div class="form-group {{ $errors->has('design.review') ? 'invalid' : '' }}">
        <label class="form-label">{{ trans('cruds.design.fields.review') }}</label>
        @foreach($this->listsForFields['review'] as $key => $value)
            <label class="radio-label"><input type="radio" name="review" wire:model="design.review" value="{{ $key }}">{{ $value }}</label>
        @endforeach
        <div class="validation-message">
            {{ $errors->first('design.review') }}
        </div>
        <div class="help-block">
            {{ trans('cruds.design.fields.review_helper') }}
        </div>
    </div>
    @if(auth()->user()->is_Admin)
        <div class="form-group {{ $errors->has('design.team_id') ? 'invalid' : '' }}">
            <label class="form-label required" for="team">{{ trans('cruds.design.fields.team') }}</label>
            <x-select-list class="form-control" required id="team" name="team" :options="$this->listsForFields['team']" wire:model="design.team_id" />
            <div class="validation-message">
                {{ $errors->first('design.team_id') }}
            </div>
            <div class="help-block">
                {{ trans('cruds.design.fields.team_helper') }}
            </div>
        </div>
    @endif
    <div class="form-group">
        <button class="btn btn-indigo mr-2" type="submit">
            {{ trans('global.save') }}
        </button>
        <a href="{{ route('admin.designs.index') }}" class="btn btn-secondary">
            {{ trans('global.cancel') }}
        </a>
    </div>
</form>

here is the Design Model :-

<?php

namespace App\Models;

use App\Support\HasAdvancedFilter;
use App\Traits\Auditable;
use App\Traits\Tenantable;
use Carbon\Carbon;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class Design extends Model implements HasMedia
{
    use HasFactory, HasAdvancedFilter, SoftDeletes, Tenantable, InteractsWithMedia, Auditable;

    public $table = 'designs';

    protected $appends = [
        'design',
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    public const CONFIRMATION_RADIO = [
        'confirmed' => 'Confirmed',
        'try again' => 'Try again',
        'edit'      => 'Edit',
    ];

    public const STATUES_RADIO = [
        'in progress' => 'In Progress',
        'published'   => 'Published',
        'scheduled'   => 'Scheduled',
    ];

    protected $fillable = [
        'project_id',
        'post_id',
        'statues',
        'confirmation',
        'note',
        'review',
        'team_id',
    ];

    public const REVIEW_RADIO = [
        'not bad'   => 'Not Good',
        'good'      => 'Good',
        'very good' => 'Very Good',
        'excellent' => 'Excellent',
        'brillent'  => 'Brillent',
    ];

    public $orderable = [
        'id',
        'project.name',
        'post.title',
        'created_at',
        'statues',
        'confirmation',
        'note',
        'review',
        'updated_at',
        'deleted_at',
        'team.name',
    ];

    public $filterable = [
        'id',
        'project.name',
        'post.title',
        'created_at',
        'statues',
        'confirmation',
        'note',
        'review',
        'updated_at',
        'deleted_at',
        'team.name',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function registerMediaConversions(Media $media = null): void
    {
        $thumbnailWidth  = 50;
        $thumbnailHeight = 50;

        $thumbnailPreviewWidth  = 120;
        $thumbnailPreviewHeight = 120;

        $this->addMediaConversion('thumbnail')
            ->width($thumbnailWidth)
            ->height($thumbnailHeight)
            ->fit('crop', $thumbnailWidth, $thumbnailHeight);
        $this->addMediaConversion('preview_thumbnail')
            ->width($thumbnailPreviewWidth)
            ->height($thumbnailPreviewHeight)
            ->fit('crop', $thumbnailPreviewWidth, $thumbnailPreviewHeight);
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function getDesignAttribute()
    {
        return $this->getMedia('design_design')->map(function ($item) {
            $media                      = $item->toArray();
            $media['url']               = $item->getUrl();
            $media['thumbnail']         = $item->getUrl('thumbnail');
            $media['preview_thumbnail'] = $item->getUrl('preview_thumbnail');

            return $media;
        });
    }

    public function getCreatedAtAttribute($value)
    {
        return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('project.datetime_format')) : null;
    }

    public function getStatuesLabelAttribute($value)
    {
        return static::STATUES_RADIO[$this->statues] ?? null;
    }

    public function getConfirmationLabelAttribute($value)
    {
        return static::CONFIRMATION_RADIO[$this->confirmation] ?? null;
    }

    public function getReviewLabelAttribute($value)
    {
        return static::REVIEW_RADIO[$this->review] ?? null;
    }

    public function getUpdatedAtAttribute($value)
    {
        return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('project.datetime_format')) : null;
    }

    public function getDeletedAtAttribute($value)
    {
        return $value ? Carbon::createFromFormat('Y-m-d H:i:s', $value)->format(config('project.datetime_format')) : null;
    }

    public function team()
    {
        return $this->belongsTo(Team::class);
    }
}

What's wrong in my code please help would like to complete my project this is the final issue

0 likes
1 reply
LaryAI's avatar
Level 58

Based on the code you've provided, there's a small mistake in the submit method of your Livewire component. You are trying to assign the post_id to the design instance, but you are not using the $post_id property that you've declared in the component. Instead, you are trying to assign $this->design->post_id to itself, which doesn't make sense and won't update the post_id of the design instance.

Here's the corrected submit method:

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->post_id; // Corrected line
    $this->design->save();
    $this->syncMedia();
    event(new DesignCreated($this->design));

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

Make sure that you are setting the $post_id property correctly when a post is selected in the view. If you are using wire:model to bind the selected post ID to the $post_id property, ensure that the wire:model directive is set correctly in your view:

<select wire:model="post_id" name="post" ...>
    @foreach ($posts as $post)
        <option value="{{ $post->id }}">{{ $post->title }}</option>
    @endforeach
</select>

Additionally, ensure that the Design model's $fillable property includes all the fields you want to be mass-assignable. If you have fields that are not included in the $fillable array, they will not be saved to the database when you call $this->design->save().

Lastly, check your database and ensure that the designs table is set up correctly with the appropriate columns for project_id, post_id, and any other fields you are trying to save. If the columns do not exist or there are database constraints preventing the save operation, that could also be the cause of the issue.

Please or to participate in this conversation.