Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to get two table data using Eloquent relationship in laravel

How to get data from two table
How to get data from multiple table
How to get data from multiple table if table field is same

How to get data from two table

If you want to retrieve more than one row from the other_table for each user, you should define a one-to-many relationship in your Paytm model. Here's how you can do it with an

In my Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\addcart;
class Paytm extends Model
{
    use HasFactory;
    protected $table = 'payment_paytm';
    protected $fillable = ['payment_id','   influencer_admin_id','currency','payment_status','admin_id','user_name','Pay_date','org_slug',' admin_email','influencer_email','influencer_name'];

         //status = 0, failed, 
         //status = 1, success, 
         //status = 2, processing 
  //protected $fillable = ['payment_id', 'payer_id', 'payer_email','amount','currency','payment_status','org_slug','admin_email','user_name','admin_id','slug','influencer_name','influencer_email'];
  public function otherTableData()
  {

    return $this->hasMany(addcart::class, 'admin_id', 'admin_id');

  }

  public function posts()
    {
        return $this->hasMany(Post::class);
    }

}
Enter fullscreen mode Exit fullscreen mode

In controller

public function myorder()
    {    

        $currentURL = url()->current(); 
        $id = Auth::user()->id; 
        $users = Paytm::where('admin_id', $id)->with('otherTableData')->get();

        log::info('now myorder' . $users);  
        log::info($users);
        return view('pages.myorder', compact('users', 'currentURL'));   


       // return view('pages.myorder', compact('data'));
    }
Enter fullscreen mode Exit fullscreen mode

In my blade file

<div class="col-md-12 col-lg-12" id="name_form">
    <div class="container ml-5">
      <div class="card h-100">
        <div class="card-body">
          <table class="table">
            <thead>
              <tr>
                <th>Order Id</th>
                <th>Influencer Names</th>                
                <th>Payment Id</th>
                <th>Cart Id</th>
                <th>Amount</th>
                <th>Order Status</th>
                <th>Order Date</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
                  @php
         $customIndex = 1; // Initialize the custom index variable
                @endphp
              @foreach($users as $user)
              @foreach(json_decode($user->influencer_name) as $influencer)
              @foreach ($user->otherTableData as $data) 
              <tr>
                <td>{{$customIndex}}</td>
                <td>              
                {{ $influencer }}            
                </td>                
                <td>{{$user->payment_id}}</td>
                <td>{{ $data->id}}</td>

                <td>{{$user->amount}} </td>
                <td>{{$user->payment_status}}</td>
                <td>{{ \Illuminate\Support\Str::limit($user->created_at, 10) }}</td>
                <td>
                  <button type="button" class="btn btn-sm btn-secondary view-button" data-id="{{$user->id}}">
                    Share Data
                  </button>
                </td>
              </tr>
              @php
        $customIndex++; // Increment the custom index
           @endphp
           @endforeach
           @endforeach
              @endforeach

            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
Enter fullscreen mode Exit fullscreen mode

output

Image description

Another Example

Assuming you have a Paytm model and a related other_table with a one-to-many relationship, define the relationship in your Paytm model like this:

Paytm.php:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Paytm extends Model
{
    public function otherTableData()
    {
        return $this->hasMany(OtherTable::class, 'admin_id', 'admin_id');
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, when you retrieve the data, you can load the related data using the with method and loop through the related records for each user:

$users = Paytm::where('admin_id', $id)->with('otherTableData')->get();

foreach ($users as $user) {
    echo "User ID: " . $user->id . "<br>";
    echo "User Name: " . $user->name . "<br>";

    // Access data from the 'other_table' relationship
    if ($user->otherTableData->isNotEmpty()) {
        echo "Other Table Data:<br>";
        foreach ($user->otherTableData as $data) {
            echo "Data ID: " . $data->id . "<br>";
            echo "Data Value: " . $data->yourColumn . "<br>";
        }
    } else {
        echo "No data found in 'other_table' for this user.<br>";
    }

    echo "<br>";
}
Enter fullscreen mode Exit fullscreen mode

In this example, the otherTableData relationship returns a collection of related records from the other_table. The with method loads this relationship for all the Paytm records in a single query, and you can access the related data for each user as a collection. Then, you can loop through the related records for each user and access their attributes.

This approach allows you to retrieve multiple rows from the other_table for each user and loop through them within the user's record in the collection.

Another Way

   <tbody>
                  @php
         $customIndex = 1; // Initialize the custom index variable
                @endphp
                @php
         $customIndex = 1; // Initialize the custom index variable
                @endphp
              @foreach($users as $user)

              @for ($i = 0; $i < count(json_decode($user->influencer_name)); $i++)          
              <tr>
                <td>{{$customIndex}}</td>
                <td>              
                {{ json_decode($user->influencer_name)[$i] }}          
                </td> 
                <td>{{$user->payment_id}}</td>             
                <td> 
                <a href="{{ route('paypalcart') }}">{{ json_decode($user->cart_id)[$i] }}</a></td>  
                <td>{{$user->amount}} </td>
                <td>{{$user->payment_status}}</td>
                <td>{{ \Illuminate\Support\Str::limit($user->created_at, 10) }}</td>
                <td>
                  <button type="button" class="btn btn-sm btn-secondary view-button" data-id="{{$user->id}}">
                    Share Data
                  </button>
                </td>
              </tr>
              @php
        $customIndex++; // Increment the custom index
           @endphp         
           @endfor
              @endforeach       
            </tbody>
Enter fullscreen mode Exit fullscreen mode

How to get data from multiple table

class Paytm extends Model
{
    use HasFactory;

    protected $table = 'payment_paytm';

    protected $fillable = [
        'payment_id', 'influencer_admin_id', 'currency', 'payment_status',
        'admin_id', 'user_name', 'Pay_date', 'org_slug', 'admin_email', 'influencer_email', 'influencer_name'
    ];

    public function otherTableData()
    {
        return $this->hasMany(addcart::class, 'admin_id', 'admin_id');
    }

    public function table2Data()
    {
        return $this->hasMany(Table2::class, 'admin_id', 'admin_id');
    }

    public function table3Data()
    {
        return $this->hasMany(Table3::class, 'admin_id', 'admin_id');
    }
}

Enter fullscreen mode Exit fullscreen mode
$users = Paytm::where('admin_id', $id)
    ->with('otherTableData', 'table2Data', 'table3Data')
    ->get();
Enter fullscreen mode Exit fullscreen mode

How to get data from multiple table if table field is same

$users = Paytm::where('admin_id', $id)
    ->with('otherTableData', 'table2Data', 'table3Data')
    ->select(
        'payment_paytm.*',
        'addcart.column_name as other_table_column',
        'table2.column_name as table2_column',
        'table3.column_name as table3_column'
    )
    ->get();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)