Reputation: 171
I have a problem with data of relationship many to many, first i will put my models and controllers, i use laravel 5.3
Model Lists Addresses
class ListsAddresses extends Model
{
protected $table = "addresses";
protected $fillable = ['state', 'city', 'street_number', 'neighborhood', 'cp'];
public function lists()
{
return $this->belongsToMany('App\Admin\Models\Lists', 'list_has_addresses' , 'address_id', 'list_id');
}
public function user(){
return $this->belongsTo('App\Admin\Models\User');
}
public $timestamps = false;
}
Controller Lists Addresses
public function form_edit_address( $id_list, $id_address ){
$list = Lists::find( $id_list );
$address = ListsAddresses::find( $id_address );
return view( "admin.forms.form_edit_address" )
->with( 'list', $list )
->with( 'address', $address );
}
View of Form
<div class="col-md-6" style="padding-right: 0">
<div class="form-group">
<label for="order">Orden*</label>
<input type="order" class="form-control" id="order" name="order" value="{{ $address->order }}" required>
</div><!-- /.form-group -->
</div><!-- /.col -->
My table pivot of database have the next structure
id - title - order - list_id - address_id
How I can get the value of order corresponding to the address in pivot table in my view?
EDDIT
This is the way i save the order in when i create new address
if( $address->save() ){
$address_data = array();
$address_title = htmlspecialchars( $request->input( "state" ).' '.$request->input( "city" ).' '.$request->input( "street" ).' '.$request->input( "neighborhood" ).' '.$request->input( "cp" ) );
$address_order = $request->input( "order" );
$address_data[ $address->id ] = array( 'title' => $address_title, 'order' => $address_order );
$list->addresses()->attach( $address_data );
}
Upvotes: 3
Views: 2496
Reputation: 126
Maybe first change your relation function to have a withPivot('order')
public function lists()
{
return $this->belongsToMany('App\Admin\Models\Lists',
'list_has_addresses' , 'address_id', 'list_id')
->withPivot('order');
}
Next, you're fetching the $list and $address entirely separately, right now there's no guarantee they're actually related to each other. If you're not doing Route Model binding then maybe you should have some ..OrFail() checks to abort with 404 if things aren't found:
public function form_edit_address( $id_list, $id_address )
{
$address = ListsAddresses::findOrFail( $id_address );
$list = $address->lists()->where('list_id', $id_list)->firstOrFail();
return view( "admin.forms.form_edit_address" )
->with( 'list', $list )
->with( 'address', $address );
}
I think the $list object will be the one with the pivot property, so in your view you would probably say $list->pivot->order
Upvotes: 2