Created
June 14, 2017 12:43
-
-
Save jhonattasantos/6b7989fee2e66426b29f4a5c2e8054c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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