In my Laravel application, I have different models that can be reported so I am using a polymorphic relationship. Posts, Threads and solutions are reportable and can be MorphedToMany. When I try to create a new report in my controller I get General error: 1364 Field 'reportable_id' doesn't have a default value (SQL: insert into `reports` (`channel`, `updated_at`, `created_at`) values ({"id":18,"created_at":"2020-08-20T09:37:06.000000Z","updated_at":"2020-08-20T09:37:06.000000Z","name":"marketing"}, 2020-08-21 09:13:45, 2020-08-21 09:13:45))
as an error
I followed the documentation the tutorial but I can't spot the error
here is my code with the post class as an example
post
use Illuminate\Database\Eloquent\Model;
use Cog\Contracts\Love\Reactable\Models\Reactable as ReactableContract;
use Cog\Laravel\Love\Reactable\Models\Traits\Reactable;
class Post extends Model implements ReactableContract
{
/**
* @var mixed
*/
use Reactable;
protected $fillable=['title','body'];
protected $guarded=[];
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->belongsToMany('App\Tag');
}
public function channel(){
return $this->belongsTo('App\Channel');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function reports(){
return $this->morphToMany('App\Report','reportable');
}
}
report
use Illuminate\Database\Eloquent\Model;
class Report extends Model
{
protected $guarded=[];
public function reportable(){
return $this->morphTo();
}
}
reportController
use App\Comment;
use App\Post;
use App\Report;
use App\Solution;
use App\Thread;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ReportController extends Controller
{
public function create(){
switch (\request('table')){
case 'posts':
$model=Post::find(\request('model'));
break;
case 'threads':
$model=Thread::find(\request('model'));
break;
case 'solutions':
$model=Solution::find(\request('model'));
//for now we are not implementing comments since is gonna be more complicated
}
//save model into database
$report=new Report();
$report->channel=$model->channel->name;
$model->reports()->create(['channel'=>$model->channel]);
//notify user
//redirect to channel
}
}
Solved I used MorphToMany
instead of MorphMany