BM BMS
BM BMS

Reputation: 57

Laravel : foreign key -> doesn't have a default value


Hi ! I read other questions but I don't find my answer.
I want to create data but give me this error:

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

Controller:

public function store(BannerRequest $request)
    {
        Banner::create($request->all());

        flash()->success('Success', 'Your banner has been created.');

        return back(); // temporary
    }

and my Table:

Schema::create('banners', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
            $table->string('street', 40);
            $table->string('city', 40);
            $table->string('zip', 15);
            $table->string('country', 40);
            $table->string('state', 40);
            $table->integer('price');
            $table->text('description');
            $table->timestamps();
        });

and this is my model :

 namespace App;
    use Illuminate\Database\Eloquent\Model;
    use App\Banner;
    use Symfony\Component\HttpFoundation\File\UploadedFile;

    class Photo extends Model
    {
        protected $table = 'banners_photos';
        protected $fillable = ['name', 'path', 'Thumbnail_path'];
        protected $file;

        public function banners()
        {
            return $this->belongsTo(Banner::class);
        }
        public static function formFile(UploadedFile $file)
        {
            $photo = new static;
            $photo->file = $file;
            $photo->fill([
                'name'           => $photo->fileName(),
                'path'           => $photo->filePath(),
                'Thumbnail_path' => $photo->ThumbnailPath()
            ]);
            return $photo;
        }
        public function fileName()
        {
            $name = sha1(time() . $this->file->getClientOriginalName());
            $extension = $this->file->getClientOriginalExtension();
            return "{$name}.{$extension}";
        }
        public function filePath()
        {
            return $this->baseDir() . DIRECTORY_SEPARATOR . $this->fileName();
        }
        public function ThumbnailPath()
        {
            return $this->baseDir() . '/tn-' . $this->fileName();
        }
        public function baseDir()
        {
            return 'images/photos';
        }
        public function upload()
        {
            $this->file->move($this->baseDir(), $this->fileName());
            $this->makeThumbnail();

            return $this;
        }
        public function makeThumbnail()
        {
            Image::make($this->filePath())->fit(200)->save($this->ThumbnailPath());
            return $this;
        }
    }

This code worked already and after refactoring become difficult.
Thank for your helps.

Upvotes: 1

Views: 6238

Answers (3)

Moak
Moak

Reputation: 12885

According to that message user_id is not set, therefore it's likely not present in $request->all().

If user_id is present, then you might want to check the user_id is in the $fillable property of your Banner model.

If you are trying to assign your banner to the current user, you could do something like this:

    $data = $request->all();
    $data['user_id'] = $request->user()->id;
    Banner::create($data);

Assuming all other data in the BannerRequest is correct and the user is signed in this should work.

SIDE NOTE: ->onUpdate('cascade') looks dangerous, if the user is modified the database will try and drop the banner. not sure if that is your intention.

Upvotes: 4

BM BMS
BM BMS

Reputation: 57

Solution :

In public function store :

$banner = auth()->user()->publish(new Banner($request->all()));

add public function publish in User model:

public function publish(Banner $banner)
    {
        return $this->banners()->save($banner);
    }

Upvotes: 0

Carlos Salazar
Carlos Salazar

Reputation: 1898

In your migratin you have this

$table->integer('user_id')->unsigned();

the errors is because in your request->all() you don't have an user_id field, if you need it add it, if not in your migration add

$table->integer('user_id')->unsigned()->nullable();

Upvotes: -1

Related Questions