skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    I resolved the issue with the following steps. As per Laravel Backpack I added the input field in the Blade:

    @include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])
    

    After this I added the function in the User Controller as follow:

    $request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
    $fileModel = new Picture;
          if($request->file()) {
               $fileName1 = time().'_'.$request->img1->getClientOriginalName();
               $filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
    $fileModel->name = time().'_'.$request->img1->getClientOriginalName();
    $fileModel->img1 = '/storage/' . $filePath1;
    $fileModel->save();
    }
    

    With these lines of code I was able to store the related Picture with the User.

    Thank you all for the guidelines.


  2. 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
        }
    
    Login or Signup to reply.
  3. 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');
        ])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search