0

I want to create a weblog using Laravel. Each post has many tags. I have a tag controller with a method to store new tag:

class TagController extends Controller
{
    public function store($title){
        return Tag::firstOrCreate(['title'=>$title]);
    }
}

In this case, i need to call this method from PostController:

class PostController extends Controller
...
    protected function createTagsObjects(string $csvTags){
            $tagsArray=explode(',',$csvTags);
            $tagsArray=array_unique($tagsArray);
            foreach($tagsArray as $tag ){
                //call to tag controller->store
            }
    }
}

I know it's not good practice to call controller method from another controller. I surfed the net and I got acquainted with traits and services. But i don't think they are useful for my problem. This scenario happens very often. Could you please help me what is the best practice to handle these situations? Thanks.

2 Answers2

0

You should never call a Controller method from another Controller.

Extract the logic to a Service class or in the Tag model and call it.

But in this case it's not necessary since you're calling an Eloquent method

protected function createTagsObjects(string $csvTags)
{
    $tagsArray = explode(',',$csvTags);
    $tagsArray = array_unique($tagsArray);
    foreach ($tagsArray as $tag) {
        $tagCreated = Tag::firstOrCreate(['title' => $tag]);
    }
}
Lloople
  • 1,827
  • 1
  • 17
  • 31
0
public function store($title){
  return Tag::firstOrCreate(['title'=>$title]);
}

This method is doing nothing but calling the method of default method of laravel Model. So, no need to call this TagController's method from PostController. Instead you can just call the Tag::firstOrCreate(['title'=>$title]); from the PostController which is absolutely fine.

But if you have some code blocks(e.g. methods) instead of this one line and those code blocks need to be called from another controller, then you should either move them to Service(Repository) or in the model(not preferable but sometimes it's ok).

Imran
  • 4,582
  • 2
  • 18
  • 37