dzonkile
dzonkile

Reputation: 19

Wrong Model inside imageable_type column inside photos table Laravel

I have polymorphic relationship between three tables(users, cars and pivot table photos). When I store car and photo for it that image is storing inside my photos table. I want to store it with imageable_type = App\Models\Car and not App\Models\User. I want to store it like the last one which I manually edited to show you. My Controller store car image with imageable_type = App\Models\User which is incorrect.

enter image description here

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]);
        $photo = $user->photo()->create(['file' => $name]);
        $input['photo_id'] = $photo->id; 
    }
    if(isset($user)) {
    $user->cars()->create($input);}
    return back();

Upvotes: 0

Views: 72

Answers (1)

Donkarnash
Donkarnash

Reputation: 12835

You are creating the Photo record via the User model's photo relationship hence it is getting associated with the currently logged in user's record - via this line $photo = $user->photo()->create(['file' => $name]);

Where is the data for creating a new Car?

From just what you have posted above, to create a new car and associate the uploaded photo with it, code should be like

//Assuming that $request->all() contains data to create a new Car record

// $request data should be validated before creating the new record

$car = Car::create($request->all());
 
if ($file = $request->file('photo_id')) {
    $name = time() . $file->getClientOriginalName();
    $file->move('storage/images', $name);
        
    $car->photo()->create(['file' => $name]);     
}


return back();

Upvotes: 1

Related Questions