Mitch M
Mitch M

Reputation: 157

Laravel multiple controller functions one route

What I'm trying to achieve is post all news by @foreach and between the @foreach do another @foreach to post all comments with the ID from the news post.

I'm unsure on how to pass this ID, to the getNewsComments function.

My controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\News;
use App\newsComments;


class newsController extends Controller
{
    public function getAllNews(){
        $results = News::all();
        return view('index')->with('news', $results);
    }
}

Route:

Route::get('/', 'newsController@getAllNews');

News model:

class News extends Model
{
    // set table
    protected $table = 'lg_news';


    public function newsComments(){
        return $this->hasMany('App\newsCommments');
    }
}

Comment model:

class newsComments extends Model
{
    // set table name
    protected $table = 'lg_newscomments';

}

view

@foreach ($news as $article)

  @foreach($news->$newsComments as $comment)
  @endforeach
@endforeach

Error:

Undefined variable: newsComments (View: C:\xampp\htdocs\resources\views\index.blade.php)

Upvotes: 0

Views: 2150

Answers (2)

Ylber Veliu
Ylber Veliu

Reputation: 359

You don't need multiple routes you just need to have two tables related to each other with 1:N relationship

Article (1) -> Comments (N)

Then you will create a model for each table and create the relation like explained in the Laravel documentation

One to Many relationship in Laravel

Then you will fetch all posts and pass them to the view:

public function getAllArticles()
{
 $posts = Post::all();
 return view('view-name', $posts);
}

And at the end, create a view and show posts and comments:

    @foreach($posts as $post)
     {{ $post->title }}
     {{ $post->body }}
     @foreach($post->comments as $comment)
      {{ $comment->title }}
      {{ $comment->body }}
     @endforeach
    @endforeach

Reminder: $post->comments , comments is the method name defined in the model where you create the relationship

Define route at web.php:

Route::get('/', 'ControllerName@getAllArticles');

Go to localhost:8000/ (or to your site domain if the site is hosted) to see the result

Upvotes: 1

Ylber Veliu
Ylber Veliu

Reputation: 359

Change this line:

return view('index')->with('news', $results);

to

return view('index', ['news' => $results]);

and it probably will work.

PS: with() function will set a session! It will not pass a variable to view.

Upvotes: 2

Related Questions