dimanche 19 février 2017

L5 How to use trait that hashes id but keep pivot functionality

I added hashes to my ID's using a trait. However by doing that now I can no longer use attach() or relationships.

For example this relationship does not work in my view anymore:

@foreach ($invoice->items as $item)
   
@endforeach

Here is the trait that hashes the id for me

<?php
namespace App\Traits;

use Hashids\Hashids;
use Illuminate\Database\Eloquent\Builder;

trait HashedId
{


    /**
     * Get the user's id as hashids.
     *
     * @param  $value
     * @return string
     */
    public function getIdAttribute($value)
    {
        $hashids = new \Hashids\Hashids(env('APP_KEY'),10);
        return $hashids->encode($value);
    }

    public function scopeHashId(Builder $query, $id)
    {
        $hashIds = new Hashids(env('APP_KEY'), 10);
        $id = $hashIds->decode($id)[0];

        return $query->where('id', $id);
    }
}

Invoice Model:

<?php

namespace App;

use App\Traits\HashedId;
use Illuminate\Database\Eloquent\Model;
use HipsterJazzbo\Landlord\BelongsToTenants;

class Invoice extends Model
{
    use BelongsToTenants;
    use HashedId;
    //
    protected $fillable = [
        'client_id',
        'invoice_number',
        'purchase_order',
        'invoice_note',
        'invoice_status',
        'invoice_total',
        'invoice_type',
        'sub_total',
        'balance_due',
        'due_date',
        'invoice_type',
        'user_id',
    ];

    protected $hidden = [
        'user_id'
    ];

    public function items()
    {
        return $this->belongsToMany('App\LineItem', 'invoice_items', 'invoice_id', 'item_id');
    }

    public function client()
    {
        return $this->belongsTo('App\Client');
    }

}

I have tried doing this from a controller but it feels more like a hack than the right way to do it and I still lose the ability to use things like $invoice->attach($lineItem) or $invoice->items

//Currently I have to unhash the ids in order to save them as a pivot
$hashIds = new \Hashids\Hashids(env('APP_KEY'), 10);
$invoiceId = $hashIds->decode($request->invoice_id)[0];
$lineItemId = $hashIds->decode($request->item_id)[0];

//Should have been able to use $invoice->attach($lineItemId)
DB::table('invoice_items')->insert(
  ['invoice_id' => $invoiceId, 'item_id' => $lineItemId]
);

How can I continue to use $invoice->attach($lineItem) or $invoice->items from controllers while still using the trait that hashes my ids?



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

Aucun commentaire:

Enregistrer un commentaire