Domantas Šlaičiūnas
Domantas Šlaičiūnas

Reputation: 369

Laravel filter data from relationship

I have two models: User and DumpDownloadHistory. DumpDownloadHistory stores all registered Users download history. The relationship between User and DumpDownloadHistory is OneToMany. DumpDownloadHistory stores:

  1. user_id (User who downloaded id),
  2. dataset (file name),
  3. user_ip (the ip address of the operation),
  4. downloadCost (how many Tokens has cost to download this file).

I need to find download history from the filter input. For example, find me all download history whose email is: '[email protected]'.

Me code:

  public function history(Request $request)
    {
        $downloadHistory = DumpDownloadHistory::query();

        if ($request->has('email') && $request->input('email') != '') {
          // Find all download history related to this email
        }
        if ($request->has('dataset') && $request->input('dataset') != '') {
          $downloadHistory = $downloadHistory->where('dataset', 'LIKE', '%'. $request->input('dataset') .'%');

        }

        if ($request->has('date_from') && $request->input('date_from') != '' && $request->has('date_to') && $request->input('date_to') != '') {
            $datefrom = $request->input('date_from');
            $dateto = $request->input('date_to');
            $downloadHistory = $downloadHistory->wherebetween('created_at', [$datefrom, $dateto]);
        }

        if ($request->input('hasPayed') == '1') {
          $downloadHistory = $downloadHistory->where('downloadCost', '!=', 'NULL');
        }

        $downloadHistory = $downloadHistory->get();

        return view('dumpDb.history', compact('downloadHistory'));
    }

User model:

class User extends Authenticatable
{
    use Notifiable;

    public function downloadHistorys(){
      return $this->hasMany(DumpDownloadHistory::class);
    }
}

DumpDownloadHistory model:

class DumpDownloadHistory extends Model
{

  protected $fillable = ['dataset', 'user_ip', 'downloadCost'];

  public function user(){
    return $this->belongsTo(User::class);
  }
}

Upvotes: 1

Views: 136

Answers (1)

Dan
Dan

Reputation: 5358

That should do it:

if ($request->has('email') && $email = $request->input('email') !== '') {
    $downloadHistory->whereHas('user', function (Builder $query) use ($email) {
        $query->where('email', $email)
    });
}

Take a look at the docs to read more about querying relationship existence.

Upvotes: 1

Related Questions