dillingham/interacts-with-uploads

Adds upload to request object

1.0.0 2021-04-15 21:59 UTC

This package is auto-updated.

Last update: 2021-10-09 03:34:11 UTC


README

Laravel trait adds FormRequest upload

Build Status Latest Stable Version Total Downloads twitter

Install

composer require dillingham/interacts-with-uploads

And add the following trait to your FormRequest classes

use \Dillingham\InteractsWithUploads;

Now you can call the following methods in controllers:

New uploads

$request->upload('key')
public function store(CreateProfileRequest $request) 
{
    $request->upload('banner');

    $profile = Profile::create($request->validated());

    return redirect()->route('profiles.show', $profile);
}

Store the file and add it's path to validated() for the same key: banner

This makes $profile->banner equal to /uploads/asfos8asfoafaf9q3wf.jpg

Update uploads

$request->upload('binding.key')
public function update(UpdateProfileRequest $request, Profile $profile)
{
    $request->upload('profile.banner');

    $profile->update($request->validated());

    return redirect()->route('profiles.show', $profile);
}

If the request has a new file for key, it deletes the old and uploads the new

If no new file is in the request, it will add the original file path back to validated()

So submitting null for that key will result in the same path / no changes to the model.

It will get the original file path using the key & route model binding, in this scenario.. profile

The binding profile connects a typehinted model & defined in Route:: using {binding} syntax

Manual update

If you are not using route model binding, you can manually set the path to update.

public function update(UpdateProfileRequest $request, Profile $profile)
{
    $request->updateUpload($profile, 'banner');

    $profile->update($request->validated());

    return redirect()->route('profiles.show', $profile);
}

Parameters

You can specify a few options and override the defaults.

$request->upload('banner', 'uploads', 'public');
  • uploads: is the default path within storage
  • public: is the default disk within config/filesystems

Author

@im_brian_d