Laravel: dynamic where clause with Elouquent

前端 未结 6 1235
温柔的废话
温柔的废话 2021-02-05 03:44

I am calling URL with search params which are dynamic. How could I form proper Eloquent query?

In theory:

  1. query
  2. query whe
6条回答
  •  心在旅途
    2021-02-05 04:17

    You can just use the where statement. For ex: on users table or User model, you want dynamic search on name, id. You can do this

    $where = [];
    $firstName = $request->get('first_name');
    if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
    $id = $request->get('id');
    if ($id) $where[] = ['id', $id];
    $users = User::where($where)->get();
    

    By default, it will return all the users, if anything exists in $where array, it will apply the where condition on that.

提交回复
热议问题