Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
trait ApiControllerTrait
{
protected $relationships = [];
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$with = isset($request->all()['with']) ? $request->all()['with'] : [];
if(!is_array($with)){
$with = explode(",",$with);
$this->relationships = $with;
}
//dd($with);
$limit = isset($request->all()['limit']) ? $request->all()['limit'] : 20;
$order = isset($request->all()['order']) ? $request->all()['order'] : null;
if ($order !== null) {
$order = explode(',', $order);
}
$order[0] = isset($order[0]) ? $order[0] : $this->model->getKeyName();
$order[1] = isset($order[1]) ? $order[1] : 'asc';
$where = isset($request->all()['where']) ? $request->all()['where'] : [];
$like = isset($request->all()['like']) ? $request->all()['like'] : null;
if ($like) {
$like = explode(',', $like);
$like[1] = '%' . $like[1] . '%';
}
$result = $this->model->orderBy($order[0], $order[1])
->where(function($query) use ($like) {
if ($like) {
return $query->where($like[0], 'like', $like[1]);
}
return $query;
})
->where($where)
->with($this->relationships)
->paginate($limit);
if(count(collect($result)['data']) < 1){
return response()->json(["error"=> true, "message"=>"Not Found"],404);
}
return response()->json($result);
}
public function show($id)
{
$result = $this->model->with($this->relationships())
->findOrFail($id);
return response()->json($result);
}
protected function relationships()
{
if (isset($this->relationships)) {
return $this->relationships;
}
return [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.