Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

getting common methods outside controller

Hi everybody, I have a PostContrller, I use this one to perform CRUD operatins and more with the Post Model, inside this controller I call to the method slugify() which I placed in the controller itself, now this method is also used in other controllers like Discount, Events, Pages controllers...

What would be the best way to implement my slugify method without copying and pasting it inside each of my controllers,, I'm still a newby but afaik you can only extend one class at a time so this option is out of the question since my controller already extends Controller.

Here is an excerpt of my PostController:

public function slugify($title){
        return $slugifiedTitle = Str::lower( Str::slug($title, '-') );
    }

    
    public function create(Create $request)
    {
        $post = new Post();
        $postCategory = PostCategory::findOrFail($request->input('category'));

        $post->postcategory_id = $postCategory->id;
        $post->user_id = Auth::user()->id;

        $post->url = $postCategory->url.'/'.$this->slugify($request->input('title'));
        $post->title = $request->input('title');
        $post->description = $request->input('description');
        $post->body = $request->input('body');
        $post->image = '/img/misc/default.jpg';
        $post->video = $request->input('video');
        
        if($request->hasFile('image')){
            $uploadFile = $request->file('image');
            $filename = str_random(6).'.'.$uploadFile->extension();
            $uploadFile->storeAs('uploads', $filename);
            $post->image = '/uploads/'.$filename;
        }

        $post->save();
        
        return response()->json([
            'post' => $post,
        ]);
        
    }

Thanks in advance

0 likes
5 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20

Use a trait : http://php.net/manual/en/language.oop5.traits.php

add your function in this trait, and call it at the beginning of your controller.

<?php
namespace App/Traits;

trait Slugify
{
    public function slugify($title){
        return $slugifiedTitle = Str::lower( Str::slug($title, '-') );
    }
}
class PostController extends Controller
{
  use \App\Traits\Slugify;

  public function create(Create $request)
    {
        $post = new Post();
        $postCategory = PostCategory::findOrFail($request->input('category'));

        $post->postcategory_id = $postCategory->id;
        $post->user_id = Auth::user()->id;

        $post->url = $postCategory->url.'/'.$this->slugify($request->input('title'));
        $post->title = $request->input('title');
        $post->description = $request->input('description');
        $post->body = $request->input('body');
        $post->image = '/img/misc/default.jpg';
        $post->video = $request->input('video');
        
        if($request->hasFile('image')){
            $uploadFile = $request->file('image');
            $filename = str_random(6).'.'.$uploadFile->extension();
            $uploadFile->storeAs('uploads', $filename);
            $post->image = '/uploads/'.$filename;
        }

        $post->save();
        
        return response()->json([
            'post' => $post,
        ]);
        
    }
shez1983's avatar

@VIlfago its not really a trait...

move it to a general helper class. then autoload it using composer

 "autoload": {
        "files": [
            "app/Helpers/helpers.php"
        ]
    },

or you can use namespace and use it normally...

the best way would be to create a trait or extend your models where you do something like

 /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($entity) {
          $entity->slug = Str::lower( Str::slug($title, '-') );
        });
    }
Vilfago's avatar

@shez1983 Formelly speaking.... yes, maybe. Even if the php definition is less strict than what some people think about trait

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

But I think my solution allow him to still use his code as it is now (i.e. $this->slugify()). And he can add it only in Controllers that need to have it.

@gabotronix if you want to use this function in all controllers, you can create an abstract class for example BaseController (which extends Controller) with this function, and then extends BaseController instead of Controller. But I guess some will find this uglier than the trait ;)

shez1983's avatar

@vilfago thats the key - a global helper would allow him to use it anywhere - blade too.. what i meant was that doesnt look like a candidate for trait because it restricts him and he has the added headache of adding use statements everywhere.. its a solution for sure

Gabotronix's avatar

I went with traits, traits are cool for generic functions. Might make them a few helpers in the future to try them out.

Please or to participate in this conversation.