How to fetch data from multiple table in Laravel code example
Example 1: laravel get data from multiple tables with
$user = User::select("id", "name")
->with(['positions' => function ($query) {
$query->select('name');
}, 'profile' => function ($query) {
$query->select("user_id", "company_name");
}])->get();
In User model write many to many relation with user positions (designation)
public function positions()
{
return $this->belongsToMany(\App\Position::class, 'user_position', 'user_id', 'position_id')
->withPivot(['position_id', 'user_id']);
}
In user Model relation with profile table
public function profile()
{
return $this->hasOne(Profile::class, 'user_id', 'id');
}
Example 2: laravel get data from multiple tables
use App\Models\Post;
$comments = Post::find(1)->comments;
foreach ($comments as $comment) {
}
Example 3: get data from 2 table in response laravel
$p1 = DB::table('properties')
->where('address', 'test')
->select('name', 'address');
$p2 = DB::table('properties_x')
->where('address', 'test')
->select('name', 'address');
$p = $p1->unionAll($p2);
DB::table(DB::raw("({$p->toSql()}) AS p"))
->mergeBindings($p)
->select('name', 'address')
->paginate(10);
Example 4: laravel get data from multiple tables
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}