문제

I'm wondering how to create a LEFT() string function using Laravel's query builder. This is what I'm going for and what returns the correct results for me.

MySQL version

SELECT id, title, LEFT(body, 141) AS body FROM posts

attempt at query builder

$posts = Post::select('title', 'id', DB::raw('left("body", 141)'))->orderBy('created_at')->get(3);

I don't revieve any errors and I can use {{ $post->title }}, but when I try to use the {{ $post->body }} then I see nothing.

도움이 되었습니까?

해결책

It looks like there is no need to answer the question but regarding the situation here, you are trying an excerpt like content from a field, which means you want to grab only 141 characters from body field and while this would work but you have to tweak it because LEFT function would return exactly 141 characters and it could be ended up (the last character) in the middle of a word like hel... where the word is hello and 141th character is l so it needs to be a complete word to show an excerpt and Laravel has built-in solution for this, using Str::words() method you can specify how many complete words to show so I think, you may use this as well:

Str::words($post->body, 30); // show first 30 words from the $post->body

Default is: words($value, $words = 100, $end = '...')

Str::words($post->body)

This will output, first 100 complete words from any text and it'll end with ..., so, for example, if the hello is the last word then it'll ended like hello....

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top