Search code examples
mysqllaravel-5.3eloquent

Laravel SUBSTRING on Eloquent query


Question

How do I put a limit on one of the rows in an Eloquent result?

Scenario

I need to retrieve only around 100 characters from one of the fields in my result. Currently I'm using a join statement so multiple results are being returned. I basically need only the first 100 characters from post.content

Code

public function getAll()
    {
        return Post::select('posts.id', 'posts.title', 'posts.content', 'posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
                    ->join('users', 'posts.user_id', '=', 'users.id')
                    ->get();
    }

I'm not sure how to go about putting a filter on the query to only return 100 characters. I've looked around briefly but I've not found anything useful, not to my specific scenario at least.


Solution

  • Cant test this at the moment (sorry) but what about:

    public function getAll(){
        $query = Post::select('posts.id', 'posts.title', 'posts.content','posts.views', 'posts.comments', 'posts.tags', 'posts.date_created', 'users.image_url', 'users.username', 'users.toxick')
                    ->join('users', 'posts.user_id', '=', 'users.id')
                    ->get();
    
        foreach($query as $entries){
            $entries->content = substr($entries->content, 1, 100);
        }
    
        return $query;
    }