Skip to content

store more than one file with a single record #23

Closed

Description

@GDLaw

What is the best method to store multiple files with a single record. I have a need to store an image, an mp3, and an mp4 file and associate them with a single record. I don't really need a one-many relationship since there will never be more than one of each type of file being stored. My implementation works great if I just select one file with my form, however, if I select more than one the save function errors out with this error:

Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into sermons (title, subtitle, speaker, desc, msgdate, updated_at, created_at) values (, , , , , 2014-01-14 23:46:08, 2014-01-14 23:46:08))

It's like it looses the reference to the instance of the newly created record. Here is the code from the function that handles adding a new record:

public function handleCreate()
{
    //handle create form submission
    $sermon = new Sermon;
    $sermon->title = Input::get('title');
    $sermon->subtitle = Input::get('subtitle');
    $sermon->speaker = Input::get('speaker');
    $sermon->desc = Input::get('desc');
    $sermon->msgdate = Input::get('msgdate');
    $sermon->imgfile = Input::file('imgfile');
    $sermon->mp3file = Input::file('mp3file');
    $sermon->mp4file = Input::file('mp4file');  
    $sermon->save();

    return Redirect::action('SermonsController@index');
}

I've looked for documentation on this but just cannot seem to find any. Any help would be greatly appreciated.

Activity

  1. tabennett commented on Jan 15, 2014

    @tabennett
    Contributor

    You should be able to do this by defining three different attachment types (imgfile, mp3file, and mp4file) on your sermon model and then passing those fields in as properties from your form (which is what I assume you're doing).

    public function __construct(array $attributes = array())
     {
          $this->hasAttachedFile('imgfile', [
              'styles' => [
                'medium' => '300x300',
                'thumb' => '100x100'
              ]
          ]);
    
          $this->hasAttachedFile('mp3file', ['styles'  => [] ]);
          $this->hasAttachedFile('mp4file', ['styles'  => [] ]);
    
          parent::__construct($attributes);
      }

    There are a couple of things to keep in mind here though:

    • Your mp3file and mp4file attachments shouldn't have any styles defined for them (since they aren't images), so you shouldn't even need to populate the styles array in the attachment config when declaring those (inside the constructor). The default settings should work.
    • Your properties on your form (that you're setting on the sermon model inside your handleCreate method) need to be named the same as their corresponding attachment declarations inside the Sermon model.
    • You need to create fields in your database table for each attachment you define on the model (imgfile_file_name, imgfile_file_size, etc). This is covered in the documentation. You should have 12 of them, 4 for each of your 3 attachment types. Make sure they're added to the fillable array of your Sermon model.

    The SQL error you're receiving about the title field being null isn't related to stapler. When you call save on the sermon model, it's only going to work on properties that are defined as attachments on the model. It won't touch any of the other properties (such as title, desc, etc). If you want, I can write up an example (model, form, and controller) of how I would handle this situation (multiple attachments on the same model).

  2. GDLaw commented on Jan 15, 2014

    @GDLaw
    Author

    An example would be fantastic! I believe I have followed the procedure you laid out above but both the 'create' form and the 'edit' form fail after storing the first file. Here are the code snippets for this app:

    Model:
    class Sermon extends Eloquent
    {
    use Codesleeve\Stapler\Stapler;

    public function getMsgdateAttribute($value)
    {
        return strftime('%Y-%m-%dT%H:%M:%S', strtotime($value));
    }
    
    public function __construct(array $attributes = array()) {
        $this->hasAttachedFile('imgfile', [
            'styles' => [ 'medium' => '980x550', 'thumbnail' => '230x130' ]
        ]);
    
        $this->hasAttachedFile('mp3file', [
            'styles' => []
        ]);
    
        $this->hasAttachedFile('mp4file', [
            'styles' => []
        ]);
    
    
        parent::__construct($attributes);
    

    }

    Sermon data table:

    Field Type Null Key Default Extra
    id "int(10) unsigned" NO PRI NULL auto_increment
    title varchar(128) NO NULL
    subtitle varchar(255) NO NULL
    desc varchar(512) NO NULL
    speaker varchar(128) NO NULL
    msgdate datetime NO NULL
    created_at timestamp NO "0000-00-00 00:00:00"
    updated_at timestamp NO "0000-00-00 00:00:00"
    imgfile_file_name varchar(255) YES NULL
    imgfile_file_size int(11) YES NULL
    imgfile_content_type varchar(255) YES NULL
    imgfile_updated_at timestamp YES NULL
    mp3file_file_name varchar(255) YES NULL
    mp3file_file_size int(11) YES NULL
    mp3file_content_type varchar(255) YES NULL
    mp3file_updated_at timestamp YES NULL
    mp4file_file_name varchar(255) YES NULL
    mp4file_file_size int(11) YES NULL
    mp4file_content_type varchar(255) YES NULL
    mp4file_updated_at timestamp YES NULL

    Sermon Controller for create and edit:

    public function create()
    {
        //show the create sermon form
        return View::make('/admin/sermons/create');
    }
    
    public function handleCreate()
    {
        //handle create form submission
        $sermon = new Sermon;
        $sermon->title = Input::get('title');
        $sermon->subtitle = Input::get('subtitle');
        $sermon->speaker = Input::get('speaker');
        $sermon->desc = Input::get('desc');
        $sermon->msgdate = Input::get('msgdate');
        $sermon->imgfile = Input::file('imgfile');
        $sermon->mp3file = Input::file('mp3file');
        $sermon->mp4file = Input::file('mp4file');  
        $sermon->save();
    
        return Redirect::action('SermonsController@index');
    }
    
    public function edit(Sermon $sermon)
    {
        //show the edit form
        return View::make('/admin/sermons/edit', compact('sermon'));
    }
    
    public function handleEdit()
    {
        // handle the edit form submission
        $sermon = Sermon::findOrFail(Input::get('id'));
        $sermon->title = Input::get('title');
        $sermon->subtitle = Input::get('subtitle');
        $sermon->speaker = Input::get('speaker');
        $sermon->desc = Input::get('desc');
        $sermon->msgdate = Input::get('msgdate');
        $sermon->imgfile = Input::file('imgfile');
        $sermon->mp3file = Input::file('mp3file');
        $sermon->mp4file = Input::file('mp4file');  
        $sermon->save();
    
        return Redirect::action('SermonsController@index');
    }
    

    Create Form:

        <form action="{{ action('SermonsController@handleCreate') }}" method="post" role="form" enctype="multipart/form-data">
            <div class="form-group">
                <label for="title" class="control-label">Title</label>
                <input type="text" class="form-control col-lg-8" name="title"/>
            </div>
            <div class="form-group">
                <label for="subtitle" class="control-label">Sub Title</label>
                <input type="text" class="form-control col-lg-8" name="subtitle" />
            </div>
            <div class="form-group">
                <label for="speaker" class="control-label">Speaker</label>
                <input type="text" class="form-control col-lg-6" name="speaker" />
            </div>
            <div class="form-group">
                <label for="desc" class="control-label">Description</label>
                <textarea class="form-control col-lg-8" rows="3" name="desc"></textarea>
            </div>
            <div class="form-group">
                <label for="msgdate" class="control-label">Date</label>
                <input type="datetime-local" class="form-control" name="msgdate" />
            </div>
            <div class="form-group">
                <label for="imgfile" class="control-label">Sermon Image</label>
                <input type="file" class="form-control col-lg-4" name="imgfile" />
            </div>
            <div class="form-group">
                <label for="mp3file" class="control-label">Sermon MP3</label>
                <input type="file" class="form-control col-lg-4" name="mp3file" />
            </div>
            <div class="form-group">
                <label for="mp4file" class="control-label">Sermon Insert</label>
                <input type="file" class="form-control col-lg-4" name="mp4file" />
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
                <a href="{{ action('SermonsController@index') }}" class="btn btn-link">Cancel</a>
            </div>
        </form>
    

    Edit Form:

        <form action="{{ action('SermonsController@handleEdit') }}" method="post" role="form" enctype="multipart/form-data">
            <input type="hidden" name="id" value="{{ $sermon->id }}">
            <div class="form-group">
                <label for="title">Title</label>
                <input type="text" class="form-control col-lg-8" name="title" value="{{ $sermon->title }}" />
            </div>
            <div class="form-group">
                <label for="subtitle">Sub Title</label>
                <input type="text" class="form-control col-lg-8" name="subtitle"  value="{{ $sermon->subtitle }}" />
            </div>
            <div class="form-group">
                <label for="speaker">Speaker</label>
                <input type="text" class="form-control col-lg-6" name="speaker"  value="{{ $sermon->speaker }}" />
            </div>
            <div class="form-group">
                <label for="desc">Description</label>
                <textarea class="form-control col-lg-8" rows="3" name="desc">{{ $sermon->desc }}</textarea>
            </div>
            <div class="form-group">
                <label for="msgdate">Date</label>
                <input type="datetime-local" class="form-control" name="msgdate"  value="{{ $sermon->msgdate }}" />
            </div>
            <div class="form-group">
                <label for="imgfile">Sermon Image (980x550)</label>
                <!-- Display a resized thumbnail style image belonging to a user record: -->
                <img src="{{ asset($sermon->imgfile->url('thumbnail')) }}" /><br />         
                Current file: {{ $sermon->imgfile->originalFilename() }}<br />      
                <input type="file" class="form-control col-lg-4" name="imgfile" />
            </div>
            <div class="form-group">
                <label for="mp3file">Sermon Audio File (mp3)</label>
                <!-- Display a resized thumbnail style image belonging to a user record: -->
                Current file: {{ $sermon->mp3file->originalFilename() }}<br />  
                <input type="file" class="form-control col-lg-4" name="mp3file" />
            </div>
            <div class="form-group">
                <label for="mp4file">Sermon Video File (mp4)</label>
                <!-- Display a resized thumbnail style image belonging to a user record: -->
                Current file: {{ $sermon->mp4file->originalFilename() }}<br />
                <input type="file" class="form-control col-lg-4" name="mp4file" />
            </div>
    
            <input type="submit" value="Update" class="btn btn-primary" />
            <a href="{{ action('SermonsController@index') }}" class="btn btn-link">Cancel</a>
        </form>
    

    Sorry for the lengthy comment. Thank you so much for your help!

  3. tabennett commented on Jan 15, 2014

    @tabennett
    Contributor

    I've built out a sample app using your code and am unable to replicate the problem. What version of Laravel are you using? Also, what's does a dd(Input::all()) give you inside your controller (when you attempt to upload multiple files)? Is the title property there inside your Input array?

  4. GDLaw commented on Jan 15, 2014

    @GDLaw
    Author

    Travis,

    Here is the dump from Input::all as you suggested. I did discover an issue with my configuration. I didn't allow for a large enough file size for apache server. I have increased the file size and the save did work. I am conducting further testing now., there seems to be an error being thrown in the output below for each file. I have separated these with line breaks below. Do you know what these are?:

    array(8) { ["title"]=> string(15) "The Bucket List" ["subtitle"]=> string(15) "The Bucket List" ["speaker"]=> string(15) "The Bucket List" ["desc"]=> string(15) "The Bucket List" ["msgdate"]=> string(16) "2014-01-18T01:00" ["imgfile"]=> object(Symfony\Component\HttpFoundation\File\UploadedFile)#9 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(23) "Remembering911_logo.png" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(9) "image/png" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(128526)

    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0)

    ["pathName":"SplFileInfo":private]=> string(24) "C:\xampp\tmp\php2668.tmp" ["fileName":"SplFileInfo":private]=> string(11) "php2668.tmp" } ["mp3file"]=> object(Symfony\Component\HttpFoundation\File\UploadedFile)#10 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(35) "2010-09-19 Bucket List - Part 1.mp3" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(9) "audio/mp3" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(20759363)

    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0)

    ["pathName":"SplFileInfo":private]=> string(24) "C:\xampp\tmp\php2688.tmp" ["fileName":"SplFileInfo":private]=> string(11) "php2688.tmp" } ["mp4file"]=> object(Symfony\Component\HttpFoundation\File\UploadedFile)#11 (7) { ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> bool(false) ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(70) "I Miss You Performed By Uriah Shelton and Dash Mihok (With Lyrics).mp4" ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> string(9) "video/mp4" ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(12378137)

    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=> int(0)

    ["pathName":"SplFileInfo":private]=> string(24) "C:\xampp\tmp\php284E.tmp" ["fileName":"SplFileInfo":private]=> string(11) "php284E.tmp" } }

  5. tabennett commented on Jan 15, 2014

    @tabennett
    Contributor

    Those are Symfony Uploaded File objects. They're part of Symfondy\Httpfoundation and they're what Laravel uses by default now (since version 4) for handling uploaded files. I don't see any errors there.

  6. GDLaw commented on Jan 15, 2014

    @GDLaw
    Author

    Great! - Thanks for your guidance Travis. I love your product and I will spread the word.

    Thanks again for your help.

    Glen

  7. tabennett commented on Jan 16, 2014

    @tabennett
    Contributor

    Thank you for the kind words. When I was building a test app using the code that you gave me, I couldn't help but notice that you're manually setting all of your properties both your handleEdit and handleCreate controller methods. I know I told you in my previous comment that you should set the database specific fields (12 of them for your case) to the fillable array, but I forgot that since the last two releases this isn't necessary anymore and in fact, if you add the name of your stapler attachments to the fillable array (along with the other fields on the Sermon model), you can do something like this:

    In your Sermon.php model, set your fillable array:

    /**
    * An array of properties that are fillable on this model.
    * 
    * @var array
    */
    
    protected $fillable = [
        'title',
        'subtitle',
        'speaker',
        'desc',
        'msgdate',
        'imgfile',
        'mp3file',
        'mp4file'
    ];

    In your handleCreate method, simply pass in the attributes when creating your Sermon instance:

    $sermon = new Sermon(Input::all());
    $sermon->save();
    
    return Redirect::action('SermonsController@index');

    Similarly, your handleEdit method could look like this:

    $sermon = Sermon::findOrFail(Input::get('id'));
    $sermon->fill(Input::all());
    $sermon->save();
    
    return Redirect::action('SermonsController@index');

    In essence, there's really no reason for you to have to manually set each of your fields in your controller (even your uploaded file fields; stapler will take care of those for you). Just a thought. Good luck with your app and thanks again for the kind words.

  8. GDLaw commented on Jan 16, 2014

    @GDLaw
    Author

    Thanks for this info Travis, it worked perfectly. One other thing, is there any way to validate a specific mime type on a Input::file?

  9. tabennett commented on Jan 16, 2014

    @tabennett
    Contributor

    I would just use Laravel's built in validation for that: http://laravel.com/docs/validation#rule-mimes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions