pecelchikin's avatar

SQLSTATE[HY000]: General error: 1364 Field 'id_gambar_paket' doesn't have a default value

i want to upload multiple images to a form. but before it did it, i created a table gambar_paket in the database so I can upload multiple images by making a relation with another table to fill in the form.

when I try to upload 3 images, the result is like this. how to solve it?

Here is my migration table for the multiple images gambar_paket

public function up()
    {
        Schema::create('gambar_paket', function (Blueprint $table) {
            $table->string('id_gambar_paket')->primary();
            $table->string('idpaket', 6)->nullable();
            $table->string('cover_paket')->nullable();

            $table->timestamps();
        });

        Schema::table('gambar_paket', function (Blueprint $table){
            $table->foreign('idpaket')->references('id_paket')->on('paket_preorder')->onDelete('cascade');
        });
    }

here is model for GambarPaket.php

protected $table = 'gambar_paket';

    protected $fillable = [
        'id_gambar paket',
        'idpaket',
        'cover_paket'
    ];

    protected $primaryKey = 'id_gambar_paket';

    protected $keyType = 'string';

    public $incrementing = false;

    public $timestamps = false;

i made PaketPreorder.php hasMany relation with GambarPaket.php

protected $table = 'paket_preorder';

    protected $fillable = [
            'id_paket',
            'idkatalog',
            'idbuku',
            'cover_paket',
            'nama_paket',
            'harga_paket',
            'qty_paket',
            'desc_paket',
            'slug',
            'status_paket'
    ];

    protected $primaryKey = 'id_paket';

    protected $keyType = 'string';

    public $incrementing = false;

    public $timestamps = false;

    public function gambarPaket(){
        return $this->hasMany(GambarPaket::class, 'idpaket', 'id_paket');
    }

here is PaketPreorderController.php

class PaketPreorderController extends Controller
{
    //main page paket preorder
    public function index(){
        return view('admin.paketpreorder.index');
    }

    //input data
    public function create(){

        $katalogs = Katalog::all();
        $listbuku = Buku::all();
        return view('admin.paketpreorder.create', compact('katalogs', 'listbuku'));
    }

    public function store(PaketPreorderFormRequest $request){
        $validatedData = $request->validated();

        $katalog = Katalog::findOrFail($validatedData['idkatalog']);
        $paket = $katalog->paketpreorder()->create([
            'idkatalog'     => $validatedData['idkatalog'],
            'id_paket'      => $validatedData['id_paket'],
            'idbuku'        => $validatedData['idbuku'],
            'nama_paket'    => $validatedData['nama_paket'],
            'harga_paket'   => $validatedData['harga_paket'],
            'qty_paket'     => $validatedData['qty_paket'],
            'desc_paket'    => $validatedData['desc_paket'],
            'slug'          => Str::slug($validatedData['slug']), //rada error tadi
            'status_paket'  => $request->status_paket == true ? '1' :'0'
        ]);

        if($request->hasFile('cover_paket')){
            $uploadPath = 'uploads/paketpreorder/'; //tmpt simpen gambar paket
 
            $i = 1;
            foreach($request->file('cover_paket') as $imageFile){
                $ext            = $imageFile->getClientOriginalExtension();
                $filename       = time().$i++.'.'.$ext;
                $imageFile->move('$uploadPath, $filename');
                $finalImagePathName = $uploadPath.$filename;
            
                
                $paket->gambarPaket()->create([
                    'idpaket' => $paket->id_paket, //idpaket dari GambarPaket
                    'cover_paket' => $finalImagePathName,
                ]);
            }
        }
        return redirect ('/admin/paketpreorder')->with('message', 'Data paket pre-order berhasil ditambahkan!');
    }
}

here is create.blade.php

<div class="tab-pane fade border p-3" id="gambarpaket" role="tabpanel" aria-labelledby="gambarpaket-tab">
                            <div class = "mb-3">
                                <label> Kode Gambar Paket</label>
                                <input type = "text" name = "id_gambar_paket" minlength="6" maxlength="6" placeholder="cont: GP0001" class = "form-control" />
                                    @error('id_gambar_paket') <small class = "text-danger">{{ $message }}</small>
                                    @enderror
                            </div>
                            <div class = "mb-3 mt-3">
                                <label> Unggah Gambar Paket Pre-Order</label>
                                <input type = "file" name = "cover_paket[]" multiple class = " multiple form-control">
                            </div>
                        </div>

here is PaketPreorderFormRequest.php

'cover_paket' => [
                'nullable',
            ],
 'cover_paket.*' => [
                'mimes:jpg,jpeg,png'
            ]
0 likes
5 replies
OussamaMater's avatar

Well I guess it's in your model GambarPaket.php, in the fillable attribute it should be id_gambar_paket and not id_gambar paket (you have a space instead of _ between gambar and paket).

2 likes
OussamaMater's avatar

@pecelchikin well, is it the exact same error? because I read the code, and that's the only bug I found, it needs to be in the fillable.

And I highly recommend you follow what @tray2 stated, for a better DB design.

2 likes
Sinnbeck's avatar

Be aware that mysql is really slow at indexing and using string ids. It will slow down queries by a lot

1 like
Tray2's avatar

Like @oussamamater says, make sure the columns in your fillable array, are the same as in your table. I also suggest that you use English names for your tables and columns, and that you follow the laravel naming conventions.

Primary keys should be named id and be type unsigned big integer.

$table->id('id');

Foreign key should be of the same type as primary keys, and they should be named, <table name in singular>_id.

$table->foreignId('user_id')
	->constrained()
	->cascadeOnDelete();

Oh, and read this one. https://tray2.se/posts/sqlerrm

A foreign key in my book should never be nullable, if they need to be you should switch the relationship around.

Example:

A user does not need to have a subscription, but a subscription must have a user.

In that scenario the users table should not have a subscription_id column, it's the subscriptions table that needs a user_id column.

2 likes

Please or to participate in this conversation.