Home > Software design >  Str Limit for return of article body laravel
Str Limit for return of article body laravel

Time:10-28

I have created an API for returning website articles :

    public function showAllArticles(){
    return Article::paginate(10);
}

in the article I have a text body (description) that may have a long text that I won't need, how can I put a str_limit to it ?

Default Output :

 {
  "current_page": 1,
  "data": [
    {
      "id": 1,
      "title": "Ut veniam dolorem et quia. Reprehenderit eum sed doloremque qui est. Sit rerum vel ex quia.",
      "slug": "dignissimos-rerum-doloribus-necessitatibus-sit-autem-ad-fuga-cum",
      "description": "Deleniti in soluta beatae id ipsa. Quia exercitationem est possimus reiciendis tempora odio. Et perspiciatis dolores dignissimos aperiam voluptatum.\n\nVoluptatem est in maiores porro error qui assumenda. Quaerat eaque vitae neque molestiae laboriosam quis necessitatibus. Vero ut qui sunt. Reiciendis dolorem enim eius recusandae praesentium repellendus.\n\nAd minima deleniti et placeat. Nisi veritatis neque et nobis voluptas. Doloremque officia aperiam aliquid repellendus nesciunt omnis.\n\nEt corrupti et totam est quod dolorum aliquam. Quo sit sequi distinctio inventore eveniet et ut. Ad voluptas perspiciatis incidunt sit. Voluptatem voluptas exercitationem debitis.\n\nEt hic beatae ducimus ad eligendi suscipit. Aut facilis magnam sequi id et ut. Reiciendis sequi iusto maiores nam delectus quasi.\n\nEt in officia earum dolores sunt et. Corrupti voluptatem delectus voluptates exercitationem molestiae aspernatur omnis corrupti. Consectetur sint quos vero nulla id alias. Possimus nam eius molestiae facere et non a.\n\nSint autem debitis corporis animi et beatae et. Aut occaecati nihil et temporibus perferendis. Commodi eligendi quo non et soluta. Vitae dolor sed qui distinctio numquam ad nihil.",
      "user_id": 13,
      "special": 0,
      "image": null,
      "created_at": "2021-10-27T21:36:37.000000Z",
      "updated_at": "2021-10-27T21:36:37.000000Z"
    }, ...

I want to make my "description" to have a lenth limit and add a extra "..." at the end of it. I have tried this :

   $data = Article::paginate(10);
   $data->each(function($article){
        // I can access each article with $article but I dont know how to modify it in $data
   });

CodePudding user response:

You can create an Eloquent: API Resource:

php artisan make:resource ArticleResource

And use the Str::limit helper for that property:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ArticleResource extends JsonResource
{
    /**
    * Transform the resource into an array.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return array
    */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'description' => Str::limit($this->description, 50),
            //...
        ];
    }
}

Then in your controller return the resource collection:

use App\Http\Resources\ArticleResource;
use App\Models\User;
//...

public function showAllArticles(){
    return ArticleResource::collection(Article::paginate(10));
}

CodePudding user response:

You should use the collection function map instead of each, here you can find the documentation for the function: https://laravel.com/docs/8.x/collections#method-map

The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items

EDIT: There is another solution to your issue that would be better in regard of performance, and that is to make the shortening procedure in your query instead of handling it in PHP. Solution can be found here: https://laracasts.com/discuss/channels/laravel/how-to-get-trimmed-value-via-eloquent?page=1&replyId=435130

CodePudding user response:

One solution would be with Custom Resources (like porloscerros already answeared) and one with Accesor. With accesors: You can add the method in your Article model:

use Illuminate\Support\Str;

public funtion getDescriptionAttribute($value)
{
    $words = 20;
    return Str::of($value)->words($words, ' >>>'); 
}
  • Related