mercredi 23 août 2017

Use raw $value in hasMany relationships in Laravel 5

I have a class that looks like this:

<?php
namespace App;

use App\State;
use Illuminate\Database\Eloquent\Model;

class Property
{
    /**
    * Connection state logs connected to property
    */
    public function states() {
        return $this->hasMany('App\State', 'property_ip', 'ip');
    }

    /**
     * Always force ips to be stored as numbers and shown as strings
     * 
     * 192.168.0.2 vs 3232235522
     */
    public function setIpAttribute($value) {
        $this->attributes['ip'] = ip2long($value);
    }
    public function getIpAttribute($value) {
        return long2ip($value);
    }
}

In the database, all IPs are stored as integers but they are always shown as strings. The problem is that the mutator getIpAttribute() converts ip to a string and then the hasMany relationship states tries to look up states by the text ip when it should be looking it up by the integer ip. If I kill the mutator, everything works, but then it shows the IPs as integers which is useless to an end user.

Is there a way to have a mutator like this but to still be able to join based on the value as it comes out of the database?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2vfXtpR
via IFTTT

Aucun commentaire:

Enregistrer un commentaire