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');
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 3 tables (workflow, user, workflow_user) and I would like to select the view column of the workflow_user table.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class,'workflow_user');
}
}
class User extends Model
{
public function works()
{
//return $this->belongsToMany(Role::class);
return $this->belongsToMany(Workflow1::class,'workflow_user');
}
}
workflow_user table
class WorkflowUser extends Model
{
protected $table = 'workflow_user';
protected $fillable = [
'workflow1_id','user_id','view'
];
protected $primaryKey = 'id';
public $timestamps = false;
}
To get the data from the workflow_user table I do this
$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);
When I make this request it does not give me the data of the workflow_user(workflow1_id,user_id,view) table.
If you have a model for the pivot table, you should have it extend the Pivot class and use it in the relationship's definition.
Also, you need to manually include the fields that are not the foreign ids in the query result.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
class User extends Model
{
public function works()
{
return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
workflow_user table
class WorkflowUser extends Pivot
{
protected $table = 'workflow_user';
protected $fillable = ['workflow_id', 'user_id', 'view'];
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
->works()
->orderBy('created_at', 'desc')
->paginate(10);
I'm beginning to think why did Laravel implement relationships to their framework, they've never worked for me and their a huge stress to fix when they break. This is the 5th time my relationships are returning null, even when ensuring I've set them up properly?
class UserStats extends Authenticatable
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function user()
{
return $this->belongsTo(User::class, 'id');
}
}
And
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stats() {
return $this->belongsTo(UserStats::class, 'user_id');
}
}
although, when calling
{{ $user->stats->some_column }}
stats is returning null... $user isn't null.
I think you have to define the owner of the relationship too. Ie:
public function stats() {
// $this->hasMany OR $this->hasOne, depending on your use case.
return $this->hasMany(UserStats::class, 'user_id');
}
We need to know here, does the user have many userstats? or the userstats have many user records? what are you planning to do here?
Here are things I noticed about your code
Your database structure is wrong. (need migrations to verify this)
Extending UserStatus from Authenticable
you have guarded id
Your relationships definitions are not correct.
To confirm we would need to look into the database structure and migrations.
If a userstat have many users and a user belongs to 1 userstat.
the migrations will be
users table will have a user_stat_id and userstats table wont have a user_id
the code will look like this.
UserStatus.php
class UserStats extends Model
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function users()
{
return $this->hasMany(User::class, 'user_stat_id');
}
}
User.php
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stat() {
return $this->belongsTo(UserStats::class, 'user_stat_id');
}
}
I want to get the name of User where belongs the foreign key using Laravel Eloquent.
I have posts Model:
Class Posts Extends Eloquent{
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
}
and
User Model:
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',
];
}
I want to send to controller the value of user name, title, text, image to view.
public function index(){
// get all the bears
$posts = Posts::all();
return View::make('welcome', compact('posts'));
}
Define the one to many relationship between the models as,
class Posts extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
// Whatever your code in Post model
}
class User extends Model
{
public function posts(){
return $this->hasMany('App\Post');
}
// Whatever your code in User model
}
as explained in the documentation here. Now you can get the name of the user that the post is belonged to each post.
Define the route as
Route::get('/all-posts','PostController#getAllPosts')->name('get_all_posts');
Write the controller class to get the posts
class PostController extends Controller
{
public function getAllPosts() {
$posts = Posts::all();
foreach ($posts as $post){
$username = $post->user->name;
//do something with $username
}
return view('all_posts')->with('detailed_posts');
//here the $detailed_posts can be defined in the 'do something' above
}
}
Here at do something you can create a new array of username and pass it to the view,
or
set the PostController as,
class PostController extends Controller
{
public function getAllPosts() {
return view(all_posts);
}
}
and then set the all_posts.blade.php to directly access the username in the view using blade syntax as follow ,
<html>
<div>
<h1>All Posts</h1>
#foreach (App\Post::all() as $post)
<span> Title : {{ $post->title}}</span>
<span> Username: {{$post->user->name}}</span>
.......
#endforeach
</div>
</html>
To set up the relationship for the Users -> Posts, then you can use hasMany
public function posts(){
return $this->hasMany('App\Post');
}
This will look for any user_id on the posts table. If it's named differently, then you can pass it in as the second parameter.
public function posts(){
return $this->hasMany('App\Post', name_of_column_in_post_table, name_of_column_in_user_table);
}
In the posts table, you want either hasOne or belongsTo. Both work the same way:
public function users() {
return $this->belongsTo('App\User', name_of_column_in_user_table, name_of_column_in_post_table);
}
You can then get the user information by doing $post->user->name
In the Model Class add the Relation like
Class Posts Extends Eloquent{
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
public function user()
{
return $this->belongsTo('App\User','user_id);
}
}
Now in the controller or view in every instance of Post you can use:
By Example
$post->user
Read the documentation about many to one relationship and even eager loading.
How to delete relation table's relations on laravel 4.2? For example, I have a table called category which is related to subcategory. So, category id is related to subcategory as foreign key and mapped for cascade delete in my migrations. Now subcategory table has relations with objects table. So subcategory id is related to objects as foreign key and mapped for cascade on delete. Now when I delete category, subcategory is getting deleted which is fine. But since subcategory is getting deleted, even objects too should get deleted right? But it is not. How to solve this?. Below is my code.
Category Model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Category extends Eloquent{
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
protected $table = "categories";
public function subcategory(){
return $this->hasMany('Subcategory', 'category_id');
}
public static function boot()
{
parent::boot();
Category::deleting(function($category) {
$category->subcategory()->delete();
});
}
}
SubCategory model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Subcategory extends Eloquent{
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
public $timestamps = false;
protected $table = "subcategories";
public function parent(){
return $this->belongsTo('Category', 'category_id');
}
public function objects(){
return $this->hasMany('Object', 'subcategory_id');
}
public static function boot()
{
parent::boot();
Subcategory::deleting(function($subcategory) {
$subcategory->objects()->delete();
});
}
}
You need to call ->delete() on each model directly to trigger associated model events
Category::deleting(function($category) {
foreach($category->subcategory as $subcategory){
$subcategory->delete();
}
});