在Laravel API控制器中创建过滤器

时间:2018-10-03 07:07:57

标签: laravel api laravel-5

嗨,我想创建一个过滤器以仅显示具有事件或活动的清真寺。有任何想法仅通过活动或事件来展示清真寺吗?来自后端的这个稍后将使用react来获取

namespace App\Http\Controllers;

use App\Event;
use App\Mosque;
use App\Activity;
use Illuminate\Http\Request;

class NotificationController extends Controller
{
    public function list()
    {
        $mosques = Mosque::get();

        $array = array();

        foreach ($mosques as $mosque) {
            array_push($array, [
                'mosque_name' => $mosque->name,
                'mosque_image'=> $mosque->image
            ]);
        }

        return $array;

        return response()->json(['result' => $mosques]);
    }

    public function show(Request $request)
    {
        $mosque =  Mosque::find($request->mosque_id);
        $mosque->activities;
        $mosque->events;

        return response()->json(['result' => $mosque]);
    }
}

2 个答案:

答案 0 :(得分:1)

要从数据库中过滤具有特定关系的行,可以在whereHas()上使用QueryBuilder Instance函数。

$mosques = Mosque::whereHas('events')
    ->orWhereHas('activities')
    ->get();

此函数将仅返回mosques which has activities or events,其他mosques将不会获取。

如果您只需要nameimage,也可以过滤它们

$mosques = Mosque::whereHas('events')
    ->orWhereHas('activities')
    ->get(['name','image']);

答案 1 :(得分:-1)

您可以尝试

  public function show(Request $request)
      {
         $mosque =  Mosque::find($request->mosque_id);
          $mosque->activities;
           $mosque->events;
         return response()->json(['result' => $mosque->events ]);
      }