0

I need to save images onto multiple controllers (bids, articles, users, etc), so it would be great to have a method that I could call from any of those controllers, what is the best way that I could implement that and how?

PS: I need such function/method because I resize, rename, crop, etc and I want to keep absolute coherence throughout my uploads

4
  • Not sure what you mean by 'save images onto multiple controllers'. If you are saving the images using an Eloquent model then you can add a processing method to the model and override and add the processing functionality into the store/update methods maybe. Commented Dec 21, 2016 at 2:11
  • I need to save images onto multiple controllers (bids, articles, users, etc), -- so, you want to save images and have that method callable from some differing controller? you could make some class and put them somewhere in app directory, then call them.. (assuming you used proper namespace and use) Commented Dec 21, 2016 at 2:12
  • @BagusTesa Exactly, I want to call the same method from various controllers from which I need to save the images onto the disk exactly in the same way in many of them. So I just create a new class that ISN'T a model, right? Commented Dec 21, 2016 at 2:18
  • @SantiagoCapdevila yes, you can add a custom class. however, do pay more attention on file location, file name, and namespace if my memory serves me right, laravel mostly uses psr-4 for autoload generation.. well, take app directory as example by noting their file location, file name, and namespace you'll able to make custom class safely. Commented Dec 21, 2016 at 2:22

2 Answers 2

1

The best way to do this is a create trait which contains relations and methods of the image model. Here is how I used it.

Crate trait Imageable.

 trait Imageable
 {

    public function images()
    {
       //code
    }
 }

Create ProductController.

<?php

use App\Traits\Imageable;

class ProductController  extends Controller
{
    use Imageable;


}

create CollectionController.

    <?php
    use App\Image;
    use App\Traits\Imageable;
    use Eloquent as Model;

    class CollectionController  extends Controller
    {
        use Imageable;
    }

Use the property of trait with this reference.

$this->images();
$this->images();
Sign up to request clarification or add additional context in comments.

Comments

1

You can add the method to the Controller.php, because the controllers extend this controller, so all the controllers will have this method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.