how to get out of the database with circumcision on the characters, it is desirable not to cut off the words

<table class="table"> <tbody> @foreach ($post as $article) <tr> <th scope="row">{{$article->id}}</th> <td>{{$article->title}}</td> <td>{{$article->slug}}</td> <td>{{$article->content}}</td> <td>{{$article->created_at}}</td> </tr> @endforeach </tbody> </table> 

Controller

 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Posts; class Blog extends Controller { public function index() { $post = Posts::orderby('created_at','desc')->paginate(5); return view('admin.pages.index')->withPost($post); } 

    1 answer 1

    I would recommend good code writing practices in the Laravel context , and also pay attention to the naming convention , since Apparently noticed a model with the name Posts (it is recommended to name the models in the singular, and the tables in the plural)

    You can create an accessor in the model to form content formatted for length.

     use Illuminate\Support\Str; class Post extends Model { // ... protected function getShortContentAttribute() { // 1. Str::words() - обрезает строку по количеству слов, переданному вторым параметром // 2. Просто совет, основанный на практике: "внутри" модели к атрибутам обращаемся // либо через ArrayAccess ($this['name']), // либо используя метод getAttribute ($this->getAttribute('name')) return Str::words((string)$this['content'], 10); } } 

    In the pattern

     <table class="table"> <tbody> @foreach ($posts as $post) <tr> <th scope="row">{{$article->id}}</th> <td>{{$post->title}}</td> <td>{{$post->slug}}</td> <!--выводим short_content (camel_case) --> <td>{{$post->short_content}}</td> <td>{{$post->created_at}}</td> </tr> @endforeach </tbody> </table>