CodeSleeve / laravel-stapler

Stapler-based file upload package for the Laravel framework.
MIT License
556 stars 109 forks source link

Iterating multiple staples #116

Closed AlexeiDarmin closed 8 years ago

AlexeiDarmin commented 8 years ago

Stapler works like a charm for one time pictures.

Is there an easy way of creating a set of staples that can be iterated over? For example a user uploads multiple avatars.

For the time being I have 6 separate forms, one for each staple, this is not scalable and involves a lot of copy paste.

riliwanrabo commented 8 years ago

I have similar issue

tabennett commented 8 years ago

Yeah you can. I used to have an example for doing this in the docs but it looks like it got removed at some point. Essentially, you need to create a separate table for your avatars and then define your attachment in that model. Then, you you need to add a hasMany relationship to your User model so that User has many avatars (or whatever you decide to name it). Then, in your file upload form you need to create an html array of file upload fields:

{{ Form::open(['url' => '/users', 'method' => 'post', 'files' => true]) }}
    {{ Form::text('first_name') }}
    {{ Form::text('last_name') }}
    {{ Form::file('files[]') }}
    {{ Form::file('files[]') }}
    {{ Form::file('files[]') }}
{{ Form::close() ?>

Then in your controller:

public function store()
{
    // Create the new user
    $user = new User(Input::get());
    $user->save();

    // Loop through each of the uploaded files:
    // 1. Create a new Avatar instance. 
    // 2. Attach the file to the new instance (stapler will process it once it's saved).
    // 3. Attach the Avatar instance to the user and save it.
    foreach(Input::file('files') as $file)
    {
        $avatar = new Avatar();             // (1)
        $avatar->file = $file;                    // (2)
        $user->avatar()->save($avatar);    // (3)
    }
}

This is taken from an old example and can probably be simplified further, but I've broken it down into discrete steps to make it easier to understand the process. This is just one way this could be done. Hope it helps!

riliwanrabo commented 8 years ago

Nice one.. Cheers @tabennett even it I found it earlier

Patroklo commented 7 years ago

Here's a package that automatizes this https://github.com/Patroklo/laravel-multiple-stapler