I have 4 tables, users
, almacenes
, detalle_alma_users
and detalle_articulos
; are related in this way:
I have a sales system, and I want that according to the warehouses to which the logged in user is related, only the articles that are related to that warehouse appear. It's giving me the error Property [almacen_id] does not exist on this collection instance.
And I think it's because of the way I'm using ->where()
it but I'm not sure how to do it and I haven't found anything on the internet.
My relationships are like this:
users
public function almacen()
{
return $this->hasMany(Almacen::class);
}
public function detallealmausers(){
return $this->hasMany(DetalleAlmaUser::class);
}
almacenes
public function detallealmausers(){
return $this->hasMany(DetalleAlmaUser::class);
}
public function user(){
return $this->belongsTo(User::class);
}
detalle_alma_users
public function almacen(){
return $this->belongsTo(Almacen::class);
}
public function user(){
return $this->belongsTo(User::class);
}
And my controller VentaController
is the following:
public function create()
{
$user = Auth::user();
$clientes = Cliente::where('user_id',Auth::user()->id)->get();
$detallearticulos = DetalleArticulo::where('almacen_id','=',$user->detallealmausers->almacen_id)->get();
$articulos = Articulo::where('estado', 'ACTIVO')->get();
$venta = Venta::get();
return view('admin.venta.create', compact('clientes', 'detallearticulos', 'articulos', 'venta'));
}
Laravel in its documentation shows that for Many to Many relationships, the models must go as follows:
In the warehouse model:
To consult and bring the information of the tables related tables you can do it in the following way: For example in the controller of your user:
In this way it helped me to consult tables with a many to many relationship, I hope it works for you. Here I leave you the documentation of laravel (english) so that you have an idea of how to do it Source: Documentation laravel many to many
The error that appears to you (
Property [almacen_id] does not exist on this collection instance.
), I guess is because of what I told you above, sometimes it is better to specify the foreign keys and the intermediate table because sometimes laravel assumes the names of the foreign asmytabla_id
and the intermediate tables asalmacenes_user
and you migration you may create it as:almacen_user
I ended up getting what I needed in this question , the function
whereHas()
, so I could add a search filter to the model.