I want to display in a loop the images associated with a specific id value from the database. How do I pass the value of an id to a function?

// Controller public function index() { $news = DB::table('news') ->where('posted', '=', 'true') ->simplePaginate(10); $photo = $this->photo($news->id); // ошибка здесь return View::make('index') ->with('news', $news) ->with('photo', $photo); } public function photo($id) { if(file_exists($id.'.jpg')) { return $id; } else { return 'default'; } } // View @foreach ($news as $news_item) {{ $news_item->id }} <img src='{{ $photo }}.jpg'> @endforeach 

    1 answer 1

    Of course you have an error. You are trying to take an id from a Paginator object.

    1) I would advise you to use the model and create an Article model (and specify the news table)

    2) Transfer the logic of processing photos or getting a path to the model, for example getPhotoPatch (), where you can already take $ this-> id

    then your controller will look like this:

     public function index() { $articles = Article::where('posted', '=', 'true')->paginate(10); return view('name')->with(compact('articles')) } @foreach($articles as $article) <img src="{{$article->getPhotoPatch()}}"> @endforeach