skip to Main Content

I am working on the Laravel back-end and I have a some question. Can I put some logic methods to the the models? Get data in specific format, for example. And some like this:

public function getAllWithObjects()
{
    $all_photos = [];
    
    $all_readed = $this::all()->toArray();
    
    foreach($all_readed as $photo)
    {
        $all_photos[$photo["id_object"]][] = env("APP_URL")."/api/photos/".$photo["id"];
    }

    return $all_photos;
}

Or it’s better put to the controller?

Looked for some videos and nothing else.

2

Answers


  1. Instead of doing a foreach statement to include the path of the image, you can actually insert it on the query using selectRaw and concat to joint the database field with a fixed stringg

    $result = Photo::selectRaw(
              "CONCAT('/api/photos/',object_id) as path"
         )
         ->get();
    
    Login or Signup to reply.
  2. I would suggest creating an attribute to get the object id for each model

    public function getObjectIdAttribute(): ?string
    {
      return $this->exists ? url("/api/photos/{$this->id}") : null;
    }
    

    and now your AppModelsPhoto has an object_id property, $photo->object_id

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search