0
votes

I'm actually new to Laravel Framework. Have been trying to post to the Mysql Database, I was getting an error on my Author_id.

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

Have checked everywhere but all efforts were proven abortive

Here is the Migration

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        //$table->engine = “InnoDB”;

        $table->increments('id');
        $table->integer('author_id')->unsigned();
        $table->foreign('author_id')->unique()->references('id')->on('users')->onDelete('restrict');
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('excerpt');
        $table->text('body');
        $table->unsignedInteger('user_id');
        $table->string('image')->nullable();   
        $table->timestamps();
    });



}

Here is my create.blade.php:

 <section class="content">
        <div class="row">
          <div class="col-xs-12">
            <div class="box">
              <div class="box-body">

              {!! Form::model($post, [
                    'method' => 'POST',
                    'url'  => 'backend/blog'
              ]) !!}  

             {{-- <form method="POST" action="{{ url('blog/store') }}" enctype="multipart/form-data">
                @csrf  --}}

                    <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
                        {!! Form::label('title') !!}
                        {!! Form::text('title', null, ['class' => 'form-control']) !!}

                        @if($errors->has('title'))
                        <span class="help-block">{{ $errors->first('title') }} </span>
                        @endif
                    </div>


                    <div class="form-group {{ $errors->has('slug') ? 'has-error' : '' }}">
                      {!! Form::label('slug') !!}
                      {!! Form::text('slug', null, ['class' => 'form-control'])!!}

                      @if($errors->has('slug'))
                      <span class="help-block">{{ $errors->first('slug') }} </span>
                      @endif
                      </div>

                        <div class="form-group {{ $errors->has('excerpt') ? 'has-error' : '' }}">
                          {!! Form::label('excerpt') !!}
                          {!! Form::textarea('excerpt', null, ['class' => 'form-control'])!!}

                        @if($errors->has('excerpt'))
                        <span class="help-block">{{ $errors->first('excerpt') }} </span>
                        @endif

                        </div>

                            <div class="form-group {{ $errors->has('body') ? 'has-error' : '' }}">
                              {!! Form::label('body') !!}
                              {!! Form::textarea('body', null, ['class' => 'form-control'])!!}

                        @if($errors->has('body'))
                        <span class="help-block">{{ $errors->first('body') }} </span>
                        @endif
                            </div>

                          <div class="form-group {{ $errors->has('published_at') ? 'has-error' : '' }}">
                            {!! Form::label('published_at', 'Published Date') !!}
                            {!! Form::text('published_at', null, ['class' => 'form-control', 'placeholder' => 'Y-m-d H:i:s'])!!}

                            @if($errors->has('published_at'))
                            <span class="help-block">{{ $errors->first('published_at') }} </span>
                            @endif
                            </div>

                        <div class="form-group {{ $errors->has('category_id') ? 'has-error' : '' }}">
                          {!! Form::label('category_id', 'Category') !!}
                          {!! Form::select('category_id', App\Category::pluck('title', 'id'), null, ['class' => 'form-control', 'placeholder' => 'Choose category' ]) !!}

                          @if($errors->has('category_id'))
                          <span class="help-block">{{ $errors->first('category_id') }} </span>
                          @endif
                        </div>

                        <hr>

                        {!! Form::submit('Create new post', ['class' => 'btn btn-primary']) !!}
                {!! Form::close() !!}
              </div>
              <!-- /.box-body -->
            </div>
            <!-- /.box -->
          </div>
        </div>
      <!-- ./row -->
    </section>

Here is my Post Model:

class Post extends Model

{

protected $fillable = ['title', 'slug', 'excerpt', 'body', 'user_id', 'published_at', 'category_id'];
protected $dates = ['published_at'];

public function author()
{
    return $this->belongsTo(User::Class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}
// images path
Public function getImageUrlAttribute($Value)
{
    $imageUrl = "";

if ( ! is_null($this->image))
{
    $imagePath = public_path(). "/img/" . $this->image;
    if (file_exists($imagePath)) $imageUrl = asset("img/" . $this->image);
}
return $imageUrl;

}

1
You must add nullable() function like this. $table->integer('author_id')->unsigned()->nullable();Safak Ciplak
This error means that you are not filling with data the author_id. Also this field is missing from your $fillable array or you must specify this field as nullable on your migration.Nerea
Yes I know I wasn't filling it, even when I added it to my fillable, I still get the same error. Im new to Laravel Nerea, Please guide me thanks. Under which page should I add that Safak Ciplak?365Techsolutions
You must relate the post you create with a specific user (aka author). Else set the author_id column to be nullable but this is not what you would want since posts have authorsNikos M.
Very correct at Nikos M. Nullable is not the best option in this Case. Author must be responsible for every post published. Would really appreciate if you can help me. this stage has really consumed so much of my time. Thanks In Advance.365Techsolutions

1 Answers

0
votes

For example to associate a Post to the current user (eg inside a controller method that saves the Post to db) do sth like the following:

// controller method
public function savePost( Request $request )
{
    $data = $request->validate([
        // your validation rules here..
        ]);
    $post = new Post(); // from Post model
    $post->fill($data);
    $post->author()->associate(\Auth::user()); // relate post to current user
    $post->save(); // save to db
    return view('whatever_your_view_is', []);
}

If you need more information leave a comment

In Post model make the following change:

public function author()
{
    return $this->belongsTo(User::Class, 'author_id'); // specify the column which stores the author in posts table
}

See documentation on defining relationships.