0

I am getting this error when trying to use the Str::limit in views

  ErrorException
  Undefined property: Illuminate\Pagination\LengthAwarePaginator::$body (View: C:\Users\USER\Desktop\laravels\qna\resources\views\questions\index.blade.php)

here is the code

  <div class="media-body">
      <h3 class="mt-0">{{ $question->title }}</h3>
      {{ Str::limit($questions->body, 250) }}
  </div>

Here is the controller

    namespace App\Http\Controllers;

    use App\Models\Question;
    use Illuminate\Http\Request;
    // use Illuminate\Support\Str;

    class QuestionsController extends Controller
    {
        // use Str;
        /**
        * Display a listing of the resource.
        *
        * @return \Illuminate\Http\Response
        */
        public function index()
        {
            $questions = Question::latest()->paginate(5);

            return view('questions.index', compact('questions'));
        }

    ...

    }

I get his error when "Str" is un-commented

    Symfony\Component\ErrorHandler\Error\FatalError
    App\Http\Controllers\QuestionsController cannot use Illuminate\Support\Str - it is not a trait

What is the proper method to use Str:: in a view

3 Answers3

2
  1. Write $question->body instead of $questions->body in your view in order to use the object of question not the paginator.
  2. Actually you don't have to use Illuminate\Support\Str in your controller at all , because you use Str class only in your view and it's one of the aliases in laravel , take a look at config/app.php.

By the way … The (use statement) above class only shorten the namespace you must use in your code like so :

use Illuminate\Support\Str;

class QuestionsController extends Controller
{ 
    public function index()
    {
        Str::limit("Some String");
    }
}

But if you don't put this use , your code would be :

class QuestionsController extends Controller
{
    public function index()
    {
        \Illuminate\Support\Str::limit("Some String");
    }
}

whereas when we put use statement inside class , it means we are trying to use trait in our class

https://www.php.net/manual/en/language.oop5.traits.php

Waseem Alhabash
  • 498
  • 4
  • 12
0

I don't think you need to add it in your controller, so just add

use Illuminate\Support\Str;

to your model and that should allow you to use it anywhere. And then in your blade you can use

\Illuminate\Support\Str::limit($questions->body, 250)

This is a Laravel solution but I do recommend looking at this thread for a pure PHP answer Limit String Length

dz0nika
  • 882
  • 1
  • 5
  • 16
0

string limit with the end of three dots

\Illuminate\Support\Str::limit($clientName,16,'...');

darshan
  • 335
  • 3
  • 11