Fahmi Pamungkas
Fahmi Pamungkas

Reputation: 37

How to Use Function inside @foreach - Laravel

Thanks For Reading. I'm new in Laravel, i want to try to change the output of Database with @foreach blade, there is the example :

This is Route :

Route::get('/home', 'warnajati@index');

This is Controller :

public function index()
{
    $post = DB::table('posts')->get();
    return view('warnajati', ['posts'=>$post]);
}

This is Views :

 @foreach ($posts as $post)
   <div class="title"><h3>{{$post->title}}</h3></div>
 @endforeach

with Output of $post->title is "This is The Looonger Title you ever know" , and i want to make the title is shorter with Wordlimit() function i have made :

function wordlimit($text, $limit=10)
{
    if (strlen($text)>$limit) {
        # code...
        $word = mb_substr($text,0,$limit-3)."...";
    }else{
        $word =$text;
    }
};

How and Where i must place that function in laravel Project ?? please help me..

Upvotes: 0

Views: 2243

Answers (3)

MBozic
MBozic

Reputation: 1192

You can put your function in helpers.php file from libraries folder. Just make sure that you have helpers.php file autoloaded in composer.json file:

"autoload": {
    "files": [
        "libraries/helpers.php"
    ],
},

If you had to add this to your composer.json you will also have to run composer dump-autoload command from terminal.

For more info check out Best practices for custom helpers on Laravel 5.

Upvotes: 0

Saumya Rastogi
Saumya Rastogi

Reputation: 13703

You can use Laravel's Accessor for doing that like this inside a Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function getShortTitleAttribute($value)
    {
        // return shortened title here ...
    }
}

and then you can use it in blade like this:

{{ $post->short_title }}

Hope this helps!

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35337

Your function has no return value... Laravel already has this function: http://laravel.com/docs/5.3/helpers#method-str-limit

 @foreach ($posts as $post)
   <div class="title"><h3>{{ str_limit($post->title, 10) }}</h3></div>
 @endforeach

Upvotes: 3

Related Questions