Skip to content

Instantly share code, notes, and snippets.

@nivv
Last active January 24, 2016 08:58
Show Gist options
  • Save nivv/6327ad980ed569fa8084 to your computer and use it in GitHub Desktop.
Save nivv/6327ad980ed569fa8084 to your computer and use it in GitHub Desktop.
Check if relation exists
<?php
namespace App\Http\Controllers\Api;
use App\Image;
use App\Article;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Transformers\ImageTransformer;
use App\Http\Controllers\Api\ApiController;
class ImagesController extends ApiController
{
protected $imageRelation = [
'articles' => '\App\Article',
'contacts' => '\App\Contact'
];
public function index(Request $request)
{
$eagerLoad = $this->eagerLoad($request);
$paginator = Image::with($eagerLoad)->paginate($this->number);
return $this->respondWithPaginator($paginator, new ImageTransformer);
}
public function getRelatedImages(Request $request, $model, $id)
{
$name = $this->getModelName($model);
if (! $name) {
return $this->errorWrongArgs($model.' has no relation with images');
}
$resource = $name::where('id', $id)->with('images')->first();
if (! $resource) {
return $this->errorNotFound(class_basename($name).' not found');
}
return $this->respondWithCollection($resource->images, new ImageTransformer);
}
protected function getModelName($model)
{
if (isset($this->imageRelation[$model])) {
return (string) $this->imageRelation[$model];
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment