Hello,
I currently have a polymorphic relationship between, for my first step, two tables -- content and blogs.
Content will be anything that a user can submit to the community I'm building -- blogs, links, file uploads, etc.
First, my tables have the following structure:
- contents: id, title, summary, user_id, object_type, object_id, created_at, updated_at
- blogs: id, content, created_at, updated_at
I will note that I have the following under the boot() function of the AppServiceProvider:
public function boot()
{
Relation::morphMap([
'blog' => \App\Blog::class
]);
}
I have the following relationship defined in my Content model:
public function object()
{
return $this->morphTo();
}
And I have the following defined in my Blog model:
public function activity()
{
return $this->morphOne(Content::class, 'object');
}
So, when I create a blog, I need to create both a record in contents and a record in blogs, and I have it working in the store() function of my Blog controller, but I know I’m doing it an absolutely round-about way, and I’m sure I can reduce it to likely one line of code:
public function store(Request $request)
{
$validData = $this->validateBlog();
$validData['user_id'] = Auth::id();
$blog = Blog::create($validData);
$validData['object_type'] = 'blog';
$validData['object_id'] = $blog->id;
$content = Content::create($validData);
return redirect('/blog');
}
I have seen tutorials that show I should be able to do something like one of the following:
$content->object()->save($blog)
$blog->activity()->save($content)
...but I had no luck.
Can anyone tell me the most efficient way of doing this?
If there is any other information you need, please let me know! As I said, the relationship itself works — I’m able to retrieve the data using $blog->activity and $blog->object calls, but I just can’t get the insert down.
Thanks!