Reputation: 19
I have three tables in my database(users,cars and photos).
Users Table
Cars Table
Photos Table
My Models:
User.php
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
public function cars() {
return $this->hasMany('App\Models\Car', 'user_id');
}
Car.php
public function user() {
return $this->belongsTo('App\Models\User');
}
public function photo() {
return $this->morphOne('App\Models\Photo', 'imageable');
}
Photo.php
protected $path = '/storage/images/';
public function getFileAttribute($file) {
return $this->path . $file;
}
public function imageable() {
return $this->morphTo();
}
My Controller@store:
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('storage/images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$user->cars()->create($input);
return back();
Imageable_id and imageable_type aren't storing. Just NULL. Why? How to store it?
Upvotes: 0
Views: 525
Reputation: 15786
You're not using the relationship when you create the photo.
$photo = Photo::create(['file' => $name]);
It should be:
$photo = $user->photo()->create(['file' => $name]);
Also, $user->cars()->create(...)
instead of $user->cars->create(...)
Upvotes: 1