Stapler-based file upload package for the Laravel framework.

Overview

laravel-stapler

Latest Stable VersionTotal Downloads Latest Unstable Version License

Laravel-Stapler is a Stapler-based file upload package for the Laravel framework. It provides a full set of Laravel commands, a migration generator, and a cascading package config on top of the Stapler package. It also bootstraps Stapler with very sensible defaults for use with Laravel. If you are wanting to use Stapler with Laravel, it is strongly recommended that you use this package to do so.

Laravel-Stapler was created by Travis Bennett.

Requirements

This package currently requires php >= 5.4 as well as Laravel >= 4, up to 5.4 (5.4 is the last version of Laravel this package will officially support). Due to the recent inconsistencies/changes introduced into Eloquent and the fact that Laravel now ships with Disks/Flysystem support, I have decided not to try and maintain this package for future version of Laravel. I am not adding a hard requirement for Laravel <= 5.4 due to the fact that some folks are already using it in their Laravel > 5.4 projects. If you want use this package in new version of Laravel you may do so at your own risk.

If you're going to be performing image processing as part of your file upload, you'll also need GD, Gmagick, or Imagick (your preference) installed as part of your php environment.

Installation

Laravel-Stapler is distributed as a composer package, which is how it should be used in your app.

Install the package using Composer. Edit your project's composer.json file to require codesleeve/laravel-stapler.

  "require": {
    "laravel/framework": "4.*",
    "codesleeve/laravel-stapler": "1.0.*"
  }

Once this operation completes, the final step is to add the service provider.

For Laravel 4, Open app/config/app.php, and add a new item to the providers array:

    'Codesleeve\LaravelStapler\Providers\L4ServiceProvider'

For Laravel 5, Open config/app.php, and add a new item to the providers array:

    'Codesleeve\LaravelStapler\Providers\L5ServiceProvider'

Deprecations

As of 1.0.04, the 'Codesleeve\LaravelStapler\LaravelStaplerServiceProvider' service provider has been deprecated (this provider will be removed in the next major release). Instead, you should now be using the corresponding service provider for the specific version of Laravel that you're using.

migrating-from-Stapler-v1.0.0-Beta4

If you've been using Stapler (prior to v1.0.0-Beta4) in your Laravel app, you now need to be using this package instead. Uninstall Stapler (remove it from your composer.json, remove the service provider, etc) and install this package following the instructions above. Once installed, the following changes may need need to be made in your application:

  • In your models that are using Stapler, change use Codesleeve\Stapler\Stapler to use Codesleeve\Stapler\ORM\EloquentTrait. Your models will also need to implement Codesleeve\Stapler\ORM\StaplerableInterface.

  • If you published stapler's config, you'll need to rename config folder from app/config/packages/codesleeve/stapler to app/config/packages/codesleeve/laravel-stapler.

  • Image processing libraries are now referenced by their full class name from the Imagine Image package (e.g gd is now reference by Imagine\Gd\Imagine).

  • In your s3 configuration, instead of passing 'key', 'secret', 'region', and 'scheme' options, you'll now need to pass a single 's3_client_config' array containing these options (and any others you might want). These will be passed directly to the s3ClientFactory when creating an S3 client. Passing the params as an array now allows you to configure your s3 client (for a given model/attachment) however you like. See: http://docs.aws.amazon.com/aws-sdk-php/guide/latest/configuration.html#client-configuration-options

  • In your s3 configuration, instead of passing 'Bucket' and 'ACL', you'll now need to pass a single 's3_object_config' array containing these values (this is used by the S3Client::putObject() method). See: http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject

  • The ':laravel_root' interpolation has been changed to ':app_root'

Quickstart

In the document root of your application (most likely the public folder), create a folder named system and grant your application write permissions to it. For this, we're assuming the existence of an existing User model in which we're going to add an avatar image to.

In your model:

use Codesleeve\Stapler\ORM\StaplerableInterface;
use Codesleeve\Stapler\ORM\EloquentTrait;

class User extends Eloquent implements StaplerableInterface {
	use EloquentTrait;

	// Add the 'avatar' attachment to the fillable array so that it's mass-assignable on this model.
	protected $fillable = ['avatar', 'first_name', 'last_name'];

	public function __construct(array $attributes = array()) {
		$this->hasAttachedFile('avatar', [
			'styles' => [
				'medium' => '300x300',
				'thumb' => '100x100'
			]
		]);

		parent::__construct($attributes);
	}
}

Make sure that the hasAttachedFile() method is called right before parent::__construct() of your model.

From the command line, use the migration generator:

php artisan stapler:fasten users avatar
php artisan migrate

In your new view:

<?= Form::open(['url' => action('UsersController@store'), 'method' => 'POST', 'files' => true]) ?>
	<?= Form::input('first_name') ?>
	<?= Form::input('last_name') ?>
	<?= Form::file('avatar') ?>
    <?= Form::submit('save') ?>
<?= Form::close() ?>

In your controller:

public function store()
{
	// Create and save a new user, mass assigning all of the input fields (including the 'avatar' file field).
    $user = User::create(Input::all());
}

In your show view:

<img src="<?= $user->avatar->url() ?>" >
<img src="<?= $user->avatar->url('medium') ?>" >
<img src="<?= $user->avatar->url('thumb') ?>" >

To detach (reset) a file, simply assign the constant STAPLER_NULL to the attachment and the save):

$user->avatar = STAPLER_NULL;
$user->save();

This will ensure the the corresponding attachment fields in the database table record are cleared and the current file is removed from storage. The database table record itself will not be destroyed and can be used normally (or even assigned a new file upload) as needed.

Commands

fasten

This package provides a fasten command that can be used to generate migrations for adding image file fields to existing tables. The method signature for this command looks like this: php artisan stapler:fasten <tablename> <attachment>

In the quickstart example above, calling php artisan stapler:fasten users avatar followed by php artisan migrate added the following fields to the users table:

  • (string) avatar_file_name
  • (integer) avatar_file_size
  • (string) avatar_content_type
  • (timestamp) avatar_updated_at

refresh

The refresh command can be used to reprocess uploaded images on a model's attachments. It works by calling the reprocess() method on each of the model's attachments (or on specific attachments only). This is very useful for adding new styles to an existing attachment when a file has already been uploaded for that attachment.

Reprocess all attachments for the ProfilePicture model: php artisan stapler:refresh ProfilePicture

Reprocess only the photo attachment on the ProfilePicture model: php artisan stapler:refresh TestPhoto --attachments="photo"

Reprocess a list of attachments on the ProfilePicture model: php artisan stapler:refresh TestPhoto --attachments="foo, bar, baz, etc"

Troubleshooting

Before you submit an issue or create a pull request, please take a look at the Troubleshooting Section section of the Stapler package. There's a very good chance that many (if not all) of the issues you're having with this package are related to the base stapler package and have already been addressed there.

Contributing

This package is always open to contributions:

  • Master will always contain the newest work (bug fixes, new features, etc), however it may not always be stable; use at your own risk. Every new tagged release will come from the work done on master, once things have stablized, etc.
Comments
  • Files are not uploaded

    Files are not uploaded

    
    <?php namespace Acme\Entities;
    
    use Illuminate\Auth\UserTrait;
    use Illuminate\Auth\UserInterface;
    use Illuminate\Auth\Reminders\RemindableTrait;
    use Illuminate\Auth\Reminders\RemindableInterface;
    
    use Hash;
    
    use Laracasts\Presenter\PresentableTrait;
    use Watson\Validating\ValidatingTrait;
    use Codesleeve\Stapler\ORM\StaplerableInterface;
    use Codesleeve\Stapler\ORM\EloquentTrait;
    
    class User extends \Eloquent implements UserInterface, RemindableInterface, StaplerableInterface {
    
        use UserTrait, RemindableTrait, PresentableTrait, ValidatingTrait, EloquentTrait;
    
    public function __construct(array $attributes = array()) {
            $this->hasAttachedFile('avatar', [
                'styles' => [
                    'medium' => '300x300',
                    'thumb' => '100x100',
                    'gravatar' => '74x74'
                ],
                'url' => '/img/:attachment/:id_partition/:style/:filename',
                'default_url' => '/img/missing.png'
            ]);
    
            parent::__construct($attributes);
        }
    
        public static function boot()
        {
            parent::boot();
    
            static::bootStapler();
        }
    

    The record is updated in db, but no files are stored in /public/img/avatar

    What am I doing wrong?

    opened by arthurkirkosa 34
  • Tags and releases

    Tags and releases

    There are numerous fixes that enable this package to work with laravel >=5.0. They are all in dev-master. It'll be great to tag a new release. This package is beginning to feel abandoned. I love it and will hate to see that happen.

    opened by MichaelObi 10
  • Fasten command error

    Fasten command error

    Error launching fasten command:

    [InvalidArgumentException]
    No hint path defined for [stapler-l4]

    The problem is located in line 84 of FastenCommand class but I've seen that in the code the bug is fixed.

    opened by eduardoperrino 9
  • Save image from url?

    Save image from url?

    I've gotten Stapler working well for image uploads but I am wondering if there is any way I can send an image url retrieved from the Twitter API through the works instead of uploading?

    opened by ghost 8
  • Cannot access parent:: when current class scope has no parent

    Cannot access parent:: when current class scope has no parent

    After updating to the latest version I'm getting this error. Any idea?

    PHP Fatal error: Cannot access parent:: when current class scope has no parent in ..../vendor/codesleeve/stapler/src/Codesleeve/Stapler/Stapler.php on line 59

    opened by tomvo 7
  • Class 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' not found when install

    Class 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' not found when install

    Hi

    I installed LaravelStapler with the following steps:

    1. Add "codesleeve/laravel-stapler": "^1.0" into composer.json file
    2. Add 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' into providers array in config/app.php file
    3. Run composer install

    And faced the error:

    [Symfony\Component\Debug\Exception\FatalErrorException]
    Class 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' not found

    If i run composer install before add 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' into providers array in config/app.php file, no error occurs.

    It's hard for me to deploy into productions when I need to comment out 'Codesleeve\LaravelStapler\Providers\L5ServiceProvider' before composer install and uncomment after in production.

    opened by chungth 6
  • Call to undefined method [package]

    Call to undefined method [package]

        "require": {
            "laravel/framework": "5.0.*",
            "codesleeve/laravel-stapler": "dev-master"
        },
    

    after adding service provider 'Codesleeve\LaravelStapler\LaravelStaplerServiceProvider', show get error:

    exception 'BadMethodCallException' with message 'Call to undefined method [package]' in C:\OpenServer\domains\my-project\vendor\laravel\framework\src\Illuminate\Support\ServiceProvider.php:226
    
    opened by nikitakiselev 6
  • Files not being uploaded

    Files not being uploaded

    Upload works with no errors. Database information for the image is put into the database table. However, the image does not appear in "system" folder. The folder is writable and has the proper group permissions so there shouldn't be a reason for the directories and file write to be failing.

    Any ideas on what might cause this? Is there not a try/catch if the file failed to be created on the system?

    opened by rbruhn 6
  • Stapler stops working when I use certain packages in the same project.

    Stapler stops working when I use certain packages in the same project.

    I have this huge issue working with Stapler that it completely stops uploading pictures whenever I add certain packages to the same project. These packages break it so bad that I have simply removing them doesn't fix the issue. I have to recreate the whole project from scratch and be wary of not using them ever again because they break the project.

    Here are the two culprits that have caused this issue:

    https://github.com/panique/laravel-sass https://github.com/shift31/laravel-elasticsearch

    I can live without the SASS compiler since I'm using Koala instead now but the my project really requires elasticsearch. Can anyone point out why this is happening and can provide a fix for the issue

    opened by tmunzar 6
  • Auth::user()->avatar->url() is undefined

    Auth::user()->avatar->url() is undefined

    First of all, thank you for this awesome repo!

    Previously in Laravel 4 I could get the current user's profile image using: {{ asset(Auth::user()->image->url('thumb')) }} I have updated Laravel to version 5 and now the image object appears to be undefined:

    Call to a member function url() on null

    The problem in context: layout.blade.php

    Edit I worked around the issue by creating the url with str_pad () and chunk_split() functions.

    opened by publicarray 5
  • Missing src/Providers dir on local install

    Missing src/Providers dir on local install

    Hi Travis,

    I was looking for a file upload package and found yours. It looks like exactly what I need.

    However, I noticed that when I installed the package the vendor/codesleeve/laravel-stapler/src/Providers directory is missing on my end. So you may have fixed the Laravel 5 issues as seen in the following issues:

    https://github.com/CodeSleeve/laravel-stapler/issues/60 https://github.com/CodeSleeve/laravel-stapler/issues/56

    But I think it still throwing an error because of the missing directory on install from Composer. I'm trying to figure out why that directory is being excluded from the download and install by Composer.

    Thanks for all the hard work on this. I want to try and fix this on my own and send you a pull request but as I'm not familiar with Composer package layout it may take me some time. So you may be able to fix this quicker than I can.

    Again thanks for sharing your hard work with everyone.

    -Daniel

    opened by JungleGenius 5
  • PutObject maximum size exceeded error.

    PutObject maximum size exceeded error.

    Can I somehow use multipart upload provided by s3 with stapler. I am trying to upload a file which is 32GB and I am running into issues of max file size

    opened by vipul-vinsol 0
  • Is this will work with laravel 5.6

    Is this will work with laravel 5.6

    We are migrating our application from laravel 5.1 to 5.6. This package is working fine with the 5.1 but this will works fine as well with laravel 5.6 ?

    opened by alankarglobant 3
  • Update for 5.6?

    Update for 5.6?

    Any plans to updated this for 5.6? The issue when updating seems to go back to CodeSleeve/stapler and not being able to install symfony/http-foundation 4

    opened by rbruhn 18
  • get_class() expects parameter 1 to be object, null given

    get_class() expects parameter 1 to be object, null given

    I'm getting this error in one of my environments but I can't figure out why. It doesn't fail on home/login, but my internal pages it does.

    get_class() expects parameter 1 to be object, null given

    Here is more of the stack!

    in Attachment.php (line 388)
    --
    at HandleExceptions->handleError(2, 'get_class() expects parameter 1 to be object, null given', '/app/vendor/codesleeve/stapler/src/Attachment.php', 388, array())
    at get_class(null)in Attachment.php (line 388)
    at Attachment->getInstanceClass()in Stapler.php (line 177)
    at Stapler::getS3ClientInstance(object(Attachment))in Storage.php (line 27)
    

    Edit: If i change the env FILESYSTEM_DRIVER to filesystem from S3 it works fine.

    opened by iredmedia 2
  • What value to use when selecting attributes in query?

    What value to use when selecting attributes in query?

    When performing a query selecting certain columns, what is used to call attachments. For example

    Project::find(1, ['title', 'logo']);
    

    The above throws an error. If I select (*) and use $project->logo->url() it works as expected. However, I don't want to select * on all my queries.

    opened by rbruhn 0
Owner
Code Sleeve
Code Sleeve
Renamify is a package for Laravel used to rename a file before uploaded to prevent replacing exists file which has the same name to this new uploaded file.

Renamify Laravel package for renaming file before uploaded on server. Renamify is a package for Laravel used to rename a file before uploaded to preve

MB'DUSENGE Callixte 2 Oct 11, 2022
A Laravel package to upload large files

A Laravel package to upload large files

Payne 896 Dec 26, 2022
Laravel Livewire Excel Upload with Progressbar

Laravel Livewire Excel Upload with Progressbar This is sample project, that explains how to import Excel files with progress bar Steps to run project

Prabakaran T 5 Oct 6, 2022
Laravel 9 Livewire Multiple Image Upload Example

Laravel livewire multiple image upload; Through this tutorial, i am going to show you how to upload multiple image using livewire in laravel apps.

Wesley Sinde 3 Feb 23, 2022
Easy way to upload Laravel model related files from the request.

Easy way to upload laravel model related file from the requset.

Emon Khan 5 Dec 15, 2022
Sebuah aplikasi file hosting sederhana yang berguna untuk menyimpan berbagai file

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Willy Ferry 2 Nov 25, 2021
Laravel Model File Uploader package

Laravel Model File Uploader package Easy way to upload laravel model related file from the requset. Install (Via Composer) composer require plusemon/u

Emon Khan 5 Dec 15, 2022
File manager module for the Lumen PHP framework.

Lumen File Manager File manager module for the Lumen PHP framework. Please note that this module is still under active development. NOTE: Branch 5.1 i

Digia 40 Aug 20, 2022
A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

Andrew Huggins 94 Nov 22, 2022
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
Self-hosted CMS platform based on the Laravel PHP Framework.

October is a Content Management System (CMS) and web platform whose sole purpose is to make your development workflow simple again. It was born out of

October CMS 10.8k Jan 1, 2023
Fast and simple implementation of a REST API based on the Laravel Framework, Repository Pattern, Eloquent Resources, Translatability, and Swagger.

Laravel Headless What about? This allows a fast and simple implementation of a REST API based on the Laravel Framework, Repository Pattern, Eloquent R

Julien SCHMITT 6 Dec 30, 2022
PHP package to help the development of Laravel-based Telegram bots

Laravel-telegram-bot Project description goes here. This description is usually two to three lines long. It should give an overview of what the projec

CC - UFFS 6 May 10, 2021
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
Gretel is a Laravel package for adding route-based breadcrumbs to your application.

Gretel Laravel breadcrumbs right out of a fairy tale. Gretel is a Laravel package for adding route-based breadcrumbs to your application. Defining Bre

Galahad 131 Dec 31, 2022
Package to easily test crudable controllers for Laravel based API

Laravel Crudable Test This package is very usefull to easily test crudable controllers. Installation You can install package via composer. Add reposit

null 2 Jul 27, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022