Search code examples
laravelviewlaravel-8

Laravel: Error when trying to use Str::limit in views


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


Solution

    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