@jasen_gottlieb
To show data from two related tables in Laravel, you can use Eloquent relationships. Here's an example with two tables: users and posts, where each user can have many posts.
User model:
1 2 3 4 5 6 7 8 9 10 11 |
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
|
Post model:
1 2 3 4 5 6 7 8 9 10 11 |
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
namespace AppHttpControllers;
use AppModelsUser;
class UserController extends Controller
{
public function index()
{
$users = User::with('posts')->get();
return view('users.index', compact('users'));
}
}
|
In your blade view file (users.index.blade.php), you can loop through the users and their related posts like this:
1 2 3 4 5 6 7 8 |
@foreach($users as $user)
<h2>{{ $user->name }}</h2>
<ul>
@foreach($user->posts as $post)
<li>{{ $post->title }}</li>
@endforeach
</ul>
@endforeach
|
This will display each user along with their posts in a list format. Make sure to adjust the code according to your actual table structure and field names.