Laravel 5 Querying Relationship

- 1 answer

Ad

Here is the relationship 1 code:

/**
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function address()
{
    return $this->hasMany('App\IPAddress', 'group_id');
}

and relationship 2 code:

/**
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function group()
{
    return $this->belongsTo('App\IPGroups');
}

I want to get all ip addresses that belongs to specified group. I don't want to write raw queries, I need to be done with querying relationship. Does anyone has an idea?

I tried to do something like this:

 /**
 * Get IP Addresses of specified group
 * @param Request $request
 * @return mixed
 */
public function getIP(Request $request)
{
    $group = IPGroups::findOrFail($request->group_id);
    return $group->address;
}

but I need to add one where statement where I can pick only active ip addresses.

Here is the model 1 code:

    namespace App;

use Illuminate\Database\Eloquent\Model;

class IPGroups extends Model
{
    /**
     * Working Table
     * @var string
     */
    protected $table = 'ip_groups';

    /**
     * Guarded Values From Mass Assignment
     * @var array
     */
    protected $guarded = [ 'id' ];

    /**
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function address()
    {
        return $this->hasMany('App\IPAddress', 'group_id');
    }
}

and the second model code:

    namespace App;

use Illuminate\Database\Eloquent\Model;

class IPAddress extends Model
{
    /**
     * Working Table
     * @var string
     */
    protected $table = 'ips';

    /**
     * Protected Values From Mass Assignment
     * @var array
     */
    protected $fillable = [ 'group_id', 'ip', 'description', 'status' ];

    /**
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo('App\IPGroups');
    }
}
Ad

Answer

Ad

Try this, getting only the addresses with status as 'Active':

return $group->address->where('status','Active'); 

The reason this doesn't work:

return $group->address->where('status','=','Active'); 

is that the where we are using here is the where of the class Collection, which doesn't accept a comparator as second parameter as the where of the Models do.

Ad
source: stackoverflow.com
Ad