Laravel Scout - pagination eager loading - laravel

How do I eager load with Laravel Scout?
Here is my query:
$results = Submission::search($query, function ($meilisearch, $query, $options) use ($request) {
$resultsFilter = '';
if ($subchan = $request->input('subchan')) {
$resultsFilter = appendToFilter($resultsFilter, 'subchan = ' . $subchan);
}
if ($incl_nsfw = $request->input('incl_nsfw')) {
if ($incl_nsfw != 1) {
$resultsFilter = appendToFilter($resultsFilter, 'nsfw != 1');
}
} else {
$resultsFilter = appendToFilter($resultsFilter, 'nsfw != 1');
}
if ($time = $request->input('time')) {
$nowTimestamp = strtotime(Carbon\Carbon::now());
$timeString = $time;
switch ($time) {
case "hour":
$resultsFilter = appendToFilter($resultsFilter, 'created_at_ts > ' . $nowTimestamp - 3600);
break;
case "day":
$resultsFilter = appendToFilter($resultsFilter, 'created_at_ts > ' . $nowTimestamp - 86400);
break;
case "week":
$resultsFilter = appendToFilter($resultsFilter, 'created_at_ts > ' . $nowTimestamp - 604800);
break;
case "month":
$resultsFilter = appendToFilter($resultsFilter, 'created_at_ts > ' . $nowTimestamp - 2592000);
break;
case "year":
$resultsFilter = appendToFilter($resultsFilter, 'created_at_ts > ' . $nowTimestamp - 31536000);
break;
}
}
if ($resultsFilter != '') {
$options['filters'] = $resultsFilter;
}
return $meilisearch->search($query, $options);
})
->paginate(15)
->withQueryString();
but since this uses the Scout builder, traditional eager loading a relationship is not possible. For reference I'm using Meilisearch.

You could also use the query() method and pass a callback
Submission::search($query)->query(fn(Builder $query) => $query->with('relationship'))->get()
The search results will include the eager loaded relationships

Figured it out! It has to be done after the query, like so:
$results->load('owner', 'savedSubmissions');
as opposed to regular eager loading, since Scout uses its own builder.

Related

multiple voyager browse blade laravel

i have Product Model and it have bread in voyager and everything is ok.
Products have publisher_id column if null == main else int(id of publisher).
i want create multiple browse blade but one of those is default voyager blade
and another where('publisher_id','!=',null)
to show .
how to created it with route ?
thanks .
fixed with resource route
Route::resource('products/index/publisher', VoyagerProductPublisherController::class);
Route::resource('products/index/notaccept', VoyagerProductPublisherNotAcceptController::class);
and then in controllers index function write query
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('publisher_id','!=',null),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('publisher_id','!=',null), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('publisher_id','!=',null), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('publisher_id','!=',null), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.publisher';
if (view()->exists("voyager::$slug.publisher")) {
$view = "voyager::$slug.publisher";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// in controller two
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = \request()->segment(3);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$getter = 'paginate';
$search = (object)['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchNames = $dataType->browseRows->mapWithKeys(function ($row) {
return [$row['field'] => $row->getTranslatedAttribute('display_name')];
});
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
$query = $model::select($dataType->name . '.*');
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope' . ucfirst($dataType->scope))) {
$query->{$dataType->scope}();
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
$usesSoftDeletes = true;
if ($request->showSoftDeleted && $request->showSoftDeleted == 1) {
$showSoftDeleted = true;
$query = $query->onlyTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%' . $search->value . '%';
$searchField = $dataType->name . '.' . $search->key;
if ($row = $this->findSearchableRelationshipRow($dataType->rows->where('type', 'relationship'), $search->key)) {
$query->whereIn(
$searchField,
$row->details->model::where($row->details->label, $search_filter, $search_value)->pluck('id')->toArray()
);
} else {
if ($dataType->browseRows->pluck('field')->contains($search->key)) {
$query->where($searchField, $search_filter, $search_value);
}
}
}
$row = $dataType->rows->where('field', $orderBy)->firstWhere('type', 'relationship');
if ($orderBy && (in_array($orderBy, $dataType->fields()) || !empty($row))) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
if (!empty($row)) {
$query->select([
$dataType->name . '.*',
'joined.' . $row->details->label . ' as ' . $orderBy,
])->leftJoin(
$row->details->table . ' as joined',
$dataType->name . '.' . $row->details->column,
'joined.' . $row->details->key,
);
}
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder)->where('accept',0),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT)->where('accept',0), 'paginate'], request()->perPage ?? 10);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC')->where('accept',0), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name)->where('accept',0), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
//Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::guard('admin')->user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
// Define list of columns that can be sorted server side
$sortableColumns = $this->getSortableColumns($dataType->browseRows);
$view = 'voyager::bread.notaccept';
if (view()->exists("voyager::$slug.notaccept")) {
$view = "voyager::$slug.notaccept";
}
return Voyager::view($view, compact(
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortableColumns',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
thanks for view .

How to search a product by specific category in Laravel with jQuery function?

I am developing a website and I am stuck in a problem where I am not getting products by categories when I select "All Categories" its working fine but when I try to select a category it again displays me the products that are shown in "All Categories" I am not getting any clue why is it happening.
Shortly, I need to get all products as well as I need products from specific category.
i tried to do it like that:
Frontend Controller
Function for returning data into view
public function search_load($keyword) {
$Cat = "";
$Desc = 1;
$Model = 1;
$Filter = array();
if(isset($_GET['category'])) {
if($_GET['category'] != "") {
$Cat = $_GET['category'];
}
}
if(isset($_GET['desc'])) {
if($_GET['desc'] != "") {
$Desc = $_GET['desc'];
}
}
if(isset($_GET['model'])) {
if($_GET['model'] != "") {
$Model = $_GET['model'];
}
}
$Filter = ["category" => $Cat, "desc" => $Desc, "model" => $Model];
$search = $this->search_products($keyword, $Filter);
$cat = $this->get_categories();
$ProductNames = $this->product_names();
$cart_item = $this->get_cart_products();
return view("search-result", compact('cat','ProductNames','search','keyword','cart_item'));
}
Function for keyword related product searching Product
public function search_products($keyword, $filter = array()) {
$Products = Product::query();
if(!empty($filter)) {
if($filter['desc'] == "1") {
$Products = $Products->orWhere('description','like','%' . $keyword . '%');
}
if($filter['model'] == "1") {
$Products = $Products->orWhere('model_no','like','%' . $keyword . '%');
}
if($filter['category'] != "" && $filter['category'] > "0") {
$cat = $filter['category'];
// return $cat;
$Products = $Products->whereIn('parent_category', [$cat]);
}
$Products = $Products->where('name','like','%' . $keyword . '%')
->orWhere('upc_code','like','%' . $keyword . '%')
->orWhere('consumer_upc1','like','%' . $keyword . '%')
->orWhere('consumer_upc2','like','%' . $keyword . '%');
}
$Products = $Products->where('status','1')->paginate(20);
return $Products;
}
jQuery Function
function search22()
{
var SText = document.getElementById("text-search").value;
SText = SText.replace("&","amp;");
var Category = document.getElementById("category").value;
var PDesc = 1;
var PModel = 1;
var link = "/search/"+ SText;
var parameter = "";
if(SText != "")
{
if(Category != "")
{
parameter = "category=" + Category;
}
if(PDesc == "1"){
if(parameter != ""){
parameter += "&desc=1";
}
else{
parameter = "desc=1";
}
}
if(PModel == "1"){
if(parameter != ""){
parameter += "&model=1";
}
else{
parameter = "model=1";
}
}
if(parameter != ""){
link += "?" + parameter;
}
window.location.href = link;
}
}
`

How can I update a column value given a where clause in Laravel?

I've tried doing:
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
but when testing it in postman returned me 0.
enter image description here
Here's my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class ShowSummaryResultsController extends Controller
{
public function show(Request $request)
{
$usuario = $request->input('usuario');
$results = DB::table('tests')
->where('usuario_id', '=', $usuario)
->where('id_evento_test', '=', '0')
->get();
$resultsOkPROTANOPIA = 0;
$resultsNokPROTANOPIA = 0;
$resultsOkDEUTERANOPIA = 0;
$resultsNokDEUTERANOPIA = 0;
$resultsOkTRITANOPIA = 0;
$resultsNokTRITANOPIA = 0;
foreach ($results as $rows)
{
$image_id = $rows->image_id;
$resultado = $rows->resultado;
//$tipo = DB::table('images')
//->where('id', '=', $image_id)
//->get();
$image = 'App\Models\Image'::findOrFail($image_id);
$tipo_discromatopsia = $image->tipo_discromatopsia;
if ($tipo_discromatopsia == 'PROTANOPIA') {
if($resultado) {
$resultsOkPROTANOPIA +=1;
}else{
$resultsNokPROTANOPIA +=1;
}
}
elseif ($tipo_discromatopsia == 'DEUTERANOPIA') {
if($resultado) {
$resultsOkDEUTERANOPIA +=1;
}else{
$resultsNokDEUTERANOPIA +=1;
}
}
else {
if($resultado) {
$resultsOkTRITANOPIA +=1;
}else{
$resultsNokTRITANOPIA +=1;
}
}
//update event_id with a unique key
//$uniquekey = 202208271116;
//$results->id_evento_test = $uniquekey;
//$results->save();
}
$porc=0;
if (($resultsOkPROTANOPIA + $resultsNokPROTANOPIA) >0)
{ $porc=$resultsOkPROTANOPIA / ($resultsOkPROTANOPIA + $resultsNokPROTANOPIA ) * 100; }
$result[0] = array("tipo" =>'PROTANOPIA',"ResOK" =>$resultsOkPROTANOPIA,"ResNOK" =>$resultsNokPROTANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) >0)
{$porc=$resultsOkDEUTERANOPIA / ($resultsOkDEUTERANOPIA + $resultsNokDEUTERANOPIA ) * 100;}
$result[1] = array("tipo" =>'DEUTERANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$porc=0;
if (($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )>0)
{$porc=$resultsOkTRITANOPIA/ ($resultsOkTRITANOPIA + $resultsNokTRITANOPIA )* 100;}
$result[2] = array("tipo" =>'TRITANOPIA',"ResOK" =>$resultsOkDEUTERANOPIA,"ResNOK" =>$resultsNokDEUTERANOPIA,"Porc" =>$porc);
$min = min($result[0]['Porc'],$result[1]['Porc'],$result[2]['Porc']);
$result[3] = array("tipo" =>'RESULTADOS',"index"=>$min,"Tipo"=>$result[$min]['tipo'], );
$uniquekey = '202208271120';
$results2 =DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', '0')
->update([ 'id_evento_test'=> $uniquekey]);
return response()->json($results2, 201);
//return response()->json($result, 201);
}
}
If you need value of column after successful updating then read this example please:
$uniquekey = '202208271120';
try {
DB::table('tests')
->where('usuario_id', $usuario)
->where('id_evento_test', 0)
->update(['id_evento_test' => $uniquekey]);
$results2 = $uniquekey;
return response()->json($results2, 201);
} catch (\Illuminate\Database\QueryExeption $e) {
return response()->json(['error' => 'Unsuccessful Update']);
}
You can use first or get to retrieve all the data from table test or only column id_evento_test. So $results2 could have all data or only part of data as you need.
in this code $results2 =DB::table('tests') you are storing the result of the database query to $result2 which is 0 or 1 and 0 means that nothing was updated and 1 means that the update was done successfully.
if you want to return the $uniquekey then assign it to $result2:
$results2 = $uniquekey;
return response()->json($results2, 201);
or just return $uniquekey:
return response()->json($uniquekey, 201);

multiple orderby sorting with pagination in laravel not working

I wrote the code snippet inside my Laravel controller and I want to sort the products by product number first and then sort the previously sorted products by inventory.
My problem is that the first sort is executed inside the written command but the second sort does not happen.
My code snippet is as follows:
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$productdetail = Sa_product::leftJoin('sa_product_allproperties', 'sa_products.productid', 'sa_product_allproperties.product_id')->where('sa_products.product_status', '1');
if (isset($data['static']) && $data['static']['search_products'] != '') {
$search_word = $data['static']['search_products'];
DB::statement("SET SQL_MODE=''");//this is for fix groupby error!
$exploded_word = explode(',', $search_word);
$counter = 0;
$productdetail = $productdetail->where(function ($q) use ($exploded_word, $counter) {
$counter = 0;
foreach ($exploded_word as $word) {
if ($counter == 0) {
$q->where('sa_products.title', 'LIKE', "%{$word}%");
} else {
$q->orwhere('sa_products.title', 'LIKE', "%{$word}%");
}
$counter++;
}
});
}
$data['staticcats'] = explode(',', $data['static']['product_cats']);
if (isset($data['static']) && $data['static'] != '') {
$explodecats = explode(',', $data['static']['product_cats']);
unset($explodecats[0]);
array_pop($explodecats);
} else {
$explodecats = [];
}
if (isset($explodecats) && $explodecats != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q1) use ($explodecats, $counter) {
$counter = 0;
foreach ($explodecats as $cats) {
if ($counter == 0) {
$q1->where('sa_products.catid', 'LIKE', "%,{$cats},%");
} else {
$q1->orWhere('sa_products.catid', 'LIKE', "%,{$cats},%");
}
$counter++;
}
});
$productdetail = $productdetail->orderBy('visited_counter', 'DESC');
}
$data['staticcats'] = explode(',', $data['static']['product_brands']);
if (isset($data['static']) && $data['static'] != '') {
$explodebrands = explode(',', $data['static']['product_brands']);
unset($explodebrands[0]);
array_pop($explodebrands);
} else {
$explodebrands = [];
}
if (isset($explodebrands) && $explodebrands != []) {
$counter = 0;
$productdetail = $productdetail->where(function ($q2) use ($explodebrands, $counter) {
$counter = 0;
foreach ($explodebrands as $brands) {
if ($counter == 0) {
//$q1->where('brand_id','LIKE', "%,{$brands},%");
$q2->where('sa_products.brand_id', "{$brands}");
} else {
//$q1->orWhere('brand_id','LIKE', "%,{$brands},%");
$q2->orWhere('sa_products.brand_id', "{$brands}");
}
$counter++;
}
});
}
$productdetail = $productdetail->orderBy('sa_products.productid','DESC')->orderBy('sa_product_allproperties.stock_count','DESC')->groupBy('sa_products.productid')->paginate(20);
if (isset($productdetail) && $productdetail->count()>0)
{
$data['searched_products'] = $productdetail;
}
After executing the above code, the received products are sorted by product number, ie the orderBy('sa_products.productid', 'DESC') occurs, but the second sorting is done with the orderBy('sa_product_allproperties.stock_count', 'DESC') Which is not run for inventory sorting.
Can anyone help me solve this problem?

Best way convert json string to Laravel Query Builder?

i have a filter string, what do you think how can i convert laravel query builder? I used some ways but I wasn't sure.
filter: [["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]]
Thank you.
if ($request->get('filter')) {
$filter = json_decode($request->get('filter'));
if (gettype($filter[0]) === 'string') {
list($field, $id) = $filter;
$query->where($field, $id);
} elseif (gettype($filter[0]) === 'array') {
foreach ($filter as $value) {
if (gettype($value) === 'string') {
switch ($value) {
case 'or':
//
break;
case 'and':
//
break;
}
} elseif (gettype($value) === 'array') {
list($field, $clause, $id) = $value;
}
}
}
}
Maybe something like this:
$arr = [["id","=",2],"or",["id","=",3],"and",["name","LIKE", "%John%"]];
$query = Model::query(); // build the empty query
if(size($arr) > 0){ // if there is at least 1 element
$query->where(...$arr[0]); // apply that element
for($i = 1; $i < size($arr); $i+=2){ // for every other entry, loop through them 2 by 2 and based of the current one, apply orWhere or where
if($arr[$i] === "or")
$query->orWhere(...$arr[$i+1]);
else
$query->where(...$arr[$i+1]);
}
}
$result = $query->get();

Resources