Filter with relationship and not found exception
jyarali opened this issue · 2 comments
jyarali commented
How can I create filters for Models with relationship (filter on related Model)?
another problem, if user sends some parameters with request that is not defined as a filter, user gets Internal Server error response. I think it's better to respond with 404 not found exception, don't you?!
mohammad-fouladgar commented
How can I create filters for Models with relationship (filter on related Model)?
Suppose you have a User model. It may have an infinite numbers of Post (One-To-Many).
You wanna to filter users who have published the posts:
- Create a filter named 'PublishedPostFilter':
<?php
namespace App\EloquentFilters\User;
use Fouladgar\EloquentBuilder\Support\Foundation\Contracts\IFilter as Filter;
use Illuminate\Database\Eloquent\Builder;
class PublishedPostFilter implements Filter
{
/**
* Apply the Publish Post condition to the query.
*
* @param Builder $builder
* @param mixed $value
*
* @return Builder
*/
public function apply(Builder $builder, $value): Builder
{
return $builder->where(function ($query) use ($value) {
$query->whereHas('posts', function ($query) use ($value) {
$query->where('is_published', $value)
->whereNotNull('published_at);
});
});
}
}
- Then use the following:
// Get: http://localhost/users?filters[published_post]=1&per_page=20
respond with 404 not found exception.
It's true! and can be used as an 'NotFoundFilterException'.
<?php
namespace App\Http\Controllers;
use App\User;
use EloquentBuilder;
use Illuminate\Http\Request;
use Fouladgar\EloquentBuilder\Exceptions\NotFoundFilterException as NotFoundFilter;
use Illuminate\Support\Arr;
class UserController extends Controller
{
public function index(Request $request)
{
try {
$users = EloquentBuilder::to(
User::class,
Arr::get($request->all(),'filters',[])
);
} catch (NotFoundFilter $e) {
abort(404, $e->getMessage());
}
return response()->json(['data' => $users->get()],200);
}
}
I hope this answer is your question.
jyarali commented
thanks man, problem solved!