How to display data from 2 tables in laravel?

Member

by deron , in category: PHP Frameworks , 13 days ago

How to display data from 2 tables in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 12 days ago

@deron 

To display data from 2 tables in Laravel, you can use Eloquent ORM to retrieve data from both tables and then pass it to your view for display. Here is an example to help you understand how to do this:

  1. Define the relationship between the two tables in your Eloquent models:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Define the relationship in your first model
class Post extends Model {
    public function comments() {
        return $this->hasMany('AppComment');
    }
}

// Define the relationship in your second model
class Comment extends Model {
    public function post() {
        return $this->belongsTo('AppPost');
    }
}


  1. Retrieve the data from both tables in your controller:
1
2
3
4
5
6
7
8
9
use AppPost;
use AppComment;

public function index() {
    // Retrieve posts and related comments
    $posts = Post::with('comments')->get();

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


  1. Pass the data to your view and display it:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
@foreach($posts as $post)
    <h2>{{ $post->title }}</h2>
    <p>{{ $post->body }}</p>

    <h3>Comments</h3>
    <ul>
        @foreach($post->comments as $comment)
            <li>{{ $comment->body }}</li>
        @endforeach
    </ul>
@endforeach


This code will retrieve all posts along with their related comments and display them in your view. Make sure to replace the table names and column names with your actual database schema.