Santiago Capdevila
Santiago Capdevila

Reputation: 125

Method call from multiple controllers in laravel

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

Upvotes: 0

Views: 2006

Answers (2)

Nirav Prajapati
Nirav Prajapati

Reputation: 126

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();

Upvotes: 1

Jes&#250;s Amieiro
Jes&#250;s Amieiro

Reputation: 2483

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

Upvotes: 1

Related Questions