In my product table for example i have this data
Laravel
Lumen
JavaScript
Eloquent
every this data maybe have prerequisite of this table, for example for Lumen user must be know laravel and for Laravel and Lumen user must be know Eloquent, how can i specify this prerequisite relationship on model?
i want to set one or many of this data on form, for example, for creating Laravel on table i can do select Eloquent or for Eloquent i can select Laravel and Lumen as an one prerequisite.
my Products model:
class Products extends Model
{
use Sluggable;
protected $table = 'products';
protected $guarded = ['id'];
protected $casts = [
'images' => 'array'
];
public function productCategories()
{
return $this->belongsToMany(ProductCategories::class);
}
public function payments()
{
return $this->hasMany(Payment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function sluggable()
{
return [
'slug' => [
'source' => 'main_title'
]
];
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
Related
I have made a separate Model and defined the required relationships between all my Many To Many Models:
class AttributeProduct extends Model
{
use HasFactory;
protected $table = 'attribute_product';
protected $guarded = [];
public function attribute()
{
return $this->belongsTo(Attribute::class, 'attribute_id', 'id');
}
public function product()
{
return $this->belongsTo(Product::class, 'product_id', 'id');
}
public function value()
{
return $this->belongsTo(Value::class, 'value_id', 'id');
}
}
For example, this Model is connected to attribute_products table.
And then I added this method to Product model:
public function attributeproducts()
{
return $this->hasMany(AttributeProduct::class, 'product_id', 'id');
}
So I wonder if it is good to make a separate model and add my own methods to it or I should use Laravel pre-defined way?
I have a relationship that is almost 5 levels deep.
In my blades I use this all time without a problem. For example:
{{ $user->team->department->region->company->name ?? ''}}
How would I go about querying all users that belong to a company?
$users = User::where($user->team->department->region->company->id, '=', 1)->get(); ?????
Company Relationships:
class Company extends Model
{
public function region() {
return $this->hasMany('App\Region', 'company_id', 'id');
}
}
Region Relationships:
class Region extends Model
{
public function company() {
return $this->hasOne('App\Company', 'id', 'company_id');
}
public function department() {
return $this->hasMany('App\Department', 'region_id', 'id');
}
}
Department Relationships:
class Department extends Model
{
public function region() {
return $this->hasOne('App\Region', 'id', 'region_id');
}
public function team() {
return $this->hasMany('App\Team', 'department_id', 'id');
}
}
Team Relationships:
class Team extends Model
{
public function department() {
return $this->hasOne('App\Department', 'id', 'department_id');
}
public function user() {
return $this->hasMany('App\User', 'team_id', 'id');
}
}
User Relationships:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function team() {
return $this->hasOne('App\Team', 'id', 'team_id');
}
}
I know there must be some easy way to query through nested relationships that Laravel provides a way for or a some facility for, but I have yet to find any decent examples from Googling around.
You can use this package for your need.
https://github.com/staudenmeir/eloquent-has-many-deep
read the instructions, depth of the relationship is not limited.
I'm getting problems calling relationships in laravel, I have 4 tables: users, tickets, stores, statuses. and I have a #OneToMany relationship in Users to Tickets (1 user have many tickets). the other relationships are #OneToOne (1 ticket have 1 store and status).
Now, I have 6 tickets in my table and 4 users, I can print the relationship to the 4 first tickets, but when I want to call the ticket 5 or 6, the relationship dissapears.
The same thing with store and status, I can print the relationship while the id of the ticket is not greater than the number of items I have in my table.
these are my models:
User Model:
class User extends Authenticatable
{
use Notifiable, HasRoles;
protected $fillable = [
'id','name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function tickets()
{
return $this->hasMany(Ticket::class, 'usuario_id');
}
}
Ticket Model:
class Ticket extends Model
{
protected $fillable = [
'comentarios', 'falla', 'modelo', 'no_serie', 'monto',
'usuario_id', 'status_id', 'store_id'
];
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function store()
{
return $this->hasOne(Store::class, 'id');
}
public function status()
{
return $this->hasOne(Status::class, 'id');
}
}
Store Model:
class Store extends Model
{
protected $table = "stores";
protected $primaryKey = 'id';
public $timestamps = false;
protected $fillable = [
'sucursal', 'dirección'
];
public function ticket()
{
return $this->belongsTo(Ticket::class, 'store_id');
}
}
Status Model:
class Status extends Model
{
public $timestamps = false;
protected $fillable = [
'status'
];
public function ticket()
{
return $this->belongsTo(Ticket::class, 'status_id');
}
}
Controller:
$tickets = Ticket::all();
return view('Admin.index', compact('tickets'));
View
#foreach($tickets as $ticket)
<li>{{ $ticket->user }}</li>
#endforeach
result:
Result of the foreach
In the view, I'm calling all the tickets ($tickets), and for each ticket, I print the relationship (user function). But in the result, you can see that just print first 4 relationships, (the number of my users), if I add 1 user, the relationship in the 5th ticket appears.
The Same problem with the other tables (store and status).
Replace user() relationship in Ticket moedel to:
public function user()
{
return $this->belongsTo(User::class, 'usuario_id', 'id');
}
in Ticket model you must change function to
public function user()
{
return $this->belongsTo(User::class, 'usuario_id', 'id');
}
or just public function user()
{
return $this->belongsTo(User::class);
}
I have two models, User and Badge. A user can have multiple badges, and a badge can belong to multiple users. (using a pivot table)
Currently I am getting the data I need, but additionally I am getting the pivot table along. How do I exclude this?
Here's the User model:
class User extends Eloquent {
public function badges() {
return $this->belongsToMany('Badge', 'users_badges');
}
}
And the Badge model:
class Badge extends Eloquent {
public function users() {
return $this->belongsToMany('User', 'users_badges');
}
}
Add pivot to your $hidden property's array in your model(s).
class Badge extends Eloquent {
protected $hidden = ['pivot'];
public function users() {
return $this->belongsToMany('User', 'users_badges');
}
}
And same with your User model
class User extends Eloquent {
protected $hidden = ['pivot'];
public function badges() {
return $this->belongsToMany('Badge', 'users_badges');
}
}
Or you can still hide the pivot on demand this way...
$user = User::find(1);
$user->badges->makeHidden('pivot');
$badge = Badge::find(1);
$badge->users->makeHidden('pivot');
Ok so I am trying to have use the Eloquent method "firstOrCreate" within another Eloquent model.
FriendRequest Eloquent
class FriendRequest extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
public $table = 'requests';
protected $guarded = array('id');
protected $softDelete = true;
public function friend() {
return $this->hasOne('User', 'id', 'friend_id');
}
public function user() {
return $this->hasOne('User', 'id', 'user_id');
}
public function accept() {
// FIRST YOU MUST MARK REQUEST AS ACCEPTED
// THEN SOFT DELETE REQUEST SO IT DOESN'T
// SHOW UP AS ACTIVE FRIEND REQUEST
$this->accepted = '1';
$this->save();
// CREATE FRIENDSHIP USER -> REQUESTED
$friend = Friend::firstOrNew(array('user_id' => Auth::user()->id, 'friend_id' => $this->friend_id));
$friend->save();
// CREATE FRIENDSHIP REQUESTED -> USER
$friend2 = Friend::firstOrNew(array('user_id' => $this->friend_id, 'friend_id' => Auth::user()->id));
$friend2->save();
// SOFT DELETE REQUEST BEING MARKED ACCEPTED
$status = $this->delete();
if (!$status):
return false;
else:
return true;
endif;
}
}
I've tried both firstOrCreate and firstOrNew as shown but with both times 'friend_id' and 'user_id' given in the array are set as '0'.
There is no default on the rows or indexes.
Here's the Friend Eloquent Model
class Friend extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
public $table = 'friends';
protected $guarded = array('id');
public function user() {
return $this->hasOne('User', 'id', 'user_id');
}
public function friend() {
return $this->hasOne('User', 'id', 'friend_id');
}
}
The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:
Set the fillable columns of your model:
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Or set only the ones you want to keep guarded:
class User extends Eloquent {
protected $guarded = array('password');
}
You may, at your own risk also do:
class User extends Eloquent {
protected $guarded = array();
}
Also on the difference between the firstorcreate, and firstornew:
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:
You can also go through the Facade and use the follwing:
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return Settings::firstOrCreate(array('name' => $settingName));
}
}
I believe you should put your accept() function in one of your controllers instead of the model. I'm not sure how and where you're calling this function, but I think it's in the wrong place.