General methods and a method accepting instances of different possible models as parameter

Posted 6 months ago by marcosdipaolo

Sorry for the blury title. This is the thing:

1st question: If a build a model that is useful for all controllers, where should I place it?. For ex. the method public function uploadImg(). Many controllers need to upload an image, so it s a method which is useful for the whole app, not a certain controller.

2nd question: If that method might be useful for upload images, it would surely need a instance of an object to store the image's urls at the right row and table, e.g. Post $post, or User $user.

If I'm consistent enough to let all models with an img column share the same image columns names at the table, say "img_url" and "thumb_ur" for thumbnails, is it posible to receive as a parameter a variable that might contain instances of different models? for example this code below (notice I'm using several methods that are not to be found in this snippet, and also the "Intervention Image" library):

public static function uploadImg($model_Instance, Request $request, $width, $prefix) 
        if ($request->hasFile('image')) {
            $ext = $request->image->extension();
            $now = time();
            $photo_path = "/img/{$prefix}/" . "{$prefix}_" . Post::slug($request->title) . "_" . $now . "." .$ext;
            $thumb_path = "/img/{$prefix}/thumbs/" . "{$prefix}thumb_" . Post::slug($request->title) . "_" . $now . "." .$ext;
            $foto = \Image::make($request->image);
            $thumb = \Image::make($request->image)->resize(150, NULL, function($c){
            if ($foto->width() > $width) {
                $foto->resize($width, NULL, function($constraint){

            $foto->save(storage_path('app/public') . $photo_path);
            $thumb->save(storage_path('app/public') . $thumb_path);
        else {
            $photo_path = $model_Instance->img ?? NULL;
            $thumb_path = $model_Instance->thumb ?? NULL;
        return ['photo_path' => $photo_path , 'thumb_path' => $thumb_path];

This is a desperate try to make this code reusable instead of copying the whole method into two different models

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.