Jump to content

Laravel 5.4 Search form with multi tables

Joveice

Hello.

To start I'm quite new to Laravel and I'm not quite sure what can be used for what.

 

I'm not sure what info I need to give on this for you to be able to help so please ask if I missed something!

 

 

So I have a search form

public function index()
    {
        $name = \Request::get('name');
        $email = \Request::get('email');
        if (($name) or ($email)) {
            $users = User::where('name', 'LIKE', '%'.$name.'%')
                ->Where('email', 'LIKE', '%'.$email.'%')
                ->paginate(10);
        }
        else {
            $users = User::paginate(10);
        }
        return view('admin.user.index', compact('users'));
    }

And I have a table with roles and a table with users in roles.

I would be able to select "Admin and Mod" and have it display all users that are in Admin or Mod.

 

This is a part of the role stuff if that can be used

public function roles()
    {
        return $this->belongsToMany('App\Role', 'role_users', 'user_id', 'role_id');
    }

    public function hasAnyRole($roles)
    {
        if (is_array($roles)) {
            foreach ($roles as $role) {
                if ($this->hasRole($role)) {
                    return true;
                }
            }
        } else {
            if ($this->hasRole($roles)) {
                return true;
            }
        }
        return false;
    }

    public function hasRole($role) {
        if ($this->roles()->where('slug', $role)->first()) {
            return true;
        }
        return false;
    }

 

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

This is what I was looking for

->whereHas('roles', function($q) {
                    $q->where('slug', 'admin');
                })

 

So this works

public function index()
    {
        $name = \Request::get('name');
        $email = \Request::get('email');
		$role = \Request::get('role');
        if (($name) or ($email)) {
            $users = User::where('name', 'LIKE', '%'.$name.'%')
                ->Where('email', 'LIKE', '%'.$email.'%')
				->whereHas('roles', function($q) use ($role) {
                    $q->where('slug', $role);
                })
                ->paginate(10);
        }
        else {
            $users = User::paginate(10);
        }
        return view('admin.user.index', compact('users'));
    }

But this only works for 1 at a time so I will have to work on it

Back-end developer, electronics "hacker"

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×