frosty frosty - 6 months ago 9
PHP Question

Use custom class in Laravel 5

In app/Library I have a file called

Helpers.php


<?php

namespace App\Library\Helpers;

class Helpers {
public function truncate($text) {
if (strlen($text) > 200) {
preg_replace('/\s+?(\S+)?$/', '', substr($text, 0, 201));
}
return $text;
}
}


In one of my views, I want to use the class:

@foreach($data['articles'] as $article)
<div class="container">
<div class="article">
<h1>{{ $article->title }}</h1>
<p>
<?php
$helpers = new \App\Library\Helpers;
echo $helpers->truncate($article->body);
?>
</p>
</div>
</div>
@endforeach


I get this error:

Class 'App\Library\Helpers' not found

Answer

You are trying to use a namespace not a class, your class is actually App\Library\Helpers\Helpers. Using blade you can use the inject method to get your class in a view.

@inject('helpers', 'App\Library\Helpers\Helpers')

@foreach($data['articles'] as $article)
    <div class="container">
        <div class="article">
            <h1>{{ $article->title }}</h1>
            <p>{{ $helpers->truncate($article->body) }}</p>
        </div>
    </div>
@endforeach

Using inject creates a new variable of the name passed as the first argument with a value of the class passed in as the second argument. Your helpers are now available in the view.

Comments