Home > Mobile >  How to upload file in relationship hasOn<->belongsTo Laravel Backpack
How to upload file in relationship hasOn<->belongsTo Laravel Backpack

Time:11-24

Can be possible to store a file uploaded to a related table? Scenario: I have a usres table in database and another one pictures. Users Model have the following function

public function picture()
    {
        return $this->hasOne(Picture::class);
    }

And the Picture Model have the following function.

public function user_picture()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

Is possible to store the picture in pictures database table (id, user_id, img_path) from the UserCrudController store() function?

CodePudding user response:

try something like this

  public function store(Request $request)
    {
      Picture::create([
       'user_id' => // get the user id from $request or auth()->user(),
       'img_path' => $request->file('image')->store('images', 'public'),
      ]);
      return // your view or something  else
    }

CodePudding user response:

Let's say it is a registration form that need to insert an image. Instead of using the Picture model directly you can just do this :

public function store(Request $request)
{
    $request->validate(...);

    $user = User::create(...);

    //It will ensure that the image belongs to the user.
    $user->picture()->create([
        'image_path' => $request->file('image')->store('images');
    ])
}
  • Related