Is reverse relation possible in laravel? - php

I'm not sure if it's name is reverse relation or not but
I have event model which contains :
public function venue()
{
return $this->hasOne('App\Models\Venue', 'id','venue_id');
}
So basicly I can access to venue data with event model but also I want to access all event data for spesific venue. I know I can do this with queries etc. but is it possible to do that with relations.
Event Migration
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->unsignedBigInteger('venue_id');
$table->decimal('price');
$table->text('content');
$table->timestamps();
$table->foreign('venue_id')->references('id')->on('venues');
Venue Migration
$table->id();
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('address');
$table->text('about');
$table->timestamps();
Event Model
public function venue()
{
return $this->hasOne('App\Models\Venue', 'id','venue_id');
}
Venue Model
public function events()
{
return $this->belongsTo(Event::class, 'venue_id','id');
}

Yes it possible. You can use belongsTo
Venue
public function events() {
return $this->hasOne(Event::class);
}
Event
public function venue()
{
return $this->belongsTo(Venue::class);
}
Then you can access like below
$venue = Venue::with('events')->where('slug',$venue_slug)->get();
foreach($venue as $key=>$value){
dd($value->events);
}

Yes! Since, one venue can have multiple events, you can define a relationship like this in Venue Model:
public function events()
{
return $this->belongsTo(Event::class);
}
See: https://laravel.com/docs/8.x/eloquent-relationships#one-to-many-inverse

Related

Laravel MorphToMany Doesn't Work for multi columns

Laravel version: 7.0 Here is my table.
Schema::create('model_email_form', function (Blueprint $table) {
$table->id();
$table->string('model_type');
$table->unsignedBigInteger('model_id');
$table->unsignedBigInteger('email_id');
$table->unsignedBigInteger('form_id');
$table->timestamps();
});
Here is my Service model.
public function forms()
{
return $this->morphToMany(
Form::class,
'model',
'model_email_form',
'model_id',
'form_id'
);
}
public function emails()
{
return $this->morphToMany(
Email::class,
'model',
'model_email_form',
'model_id',
'email_id'
);
}
I inserted data in model_email_form table but when I get service model object, emails and forms have null object.
Can anyone help me?
From your question and comments:
There are Form, Email and Service. Forms can be associated with any number of different types of models. Emails can be associated with any number of different types of models. A Service can have many Forms and a Service can have many Emails.
Using that as the basis, this would be our schema:
Schema::create('forms', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name'); // as an example
...
$table->timestamps();
});
Schema::create('formables', function (Blueprint $table) {
$table->unsignedBigInteger('form_id'); // the id of the form
$table->unsignedBigInteger('formable_id'); // the associated model's id
$table->string('formable_type'); // The associated model's class name
});
Schema::create('emails', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('subject'); // as an example
...
$table->timestamps();
});
Schema::create('emailables', function (Blueprint $table) {
$table->unsignedBigInteger('email_id'); // the id of the email
$table->unsignedBigInteger('emailable_id'); // the associated model's id
$table->string('emailable_type'); // The associated model's class name
});
Schema::create('services', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name'); // as an example
...
$table->timestamps();
});
With that schema, we can create the following models with the following relationships:
class Form extends Model
{
public function services()
{
return $this->morphedByMany(Service::class, 'formable');
}
// Add the other morphedByMany relationships of forms
}
class Email extends Model
{
public function services()
{
return $this->morphedByMany(Service::class, 'emailable');
}
// Add the other morphedByMany relationships of emails
}
class Service extends Model
{
public function forms()
{
return $this->morphedToMany(Form::class, 'formable');
}
public function emails()
{
return $this->morphedToMany(Email::class, 'emailable');
}
}

Laravel related model attributes are empty?

I'm trying to give ability on user to see his orders. I have created relationships but when i (dd) the result of the function, the related model attributes are empty.
I don't know what is wrong.
Here is my buyer function
//Buyer Orders
public function myOrders()
{
$user = User::find(auth()->user()->id);
$user = $user->products();
dd($user);// related model attributes shows empty
return view('myOrders')->with(compact('user'));
}
and here is my user
public function products()
{
return $this->hasMany(Products_model::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function allOrdersBuyerSeller()
{
return $this->hasMany(OrderProduct::class);
}
products_model
public function orders()
{
return $this->belongsToMany('App\Order', 'order_product');
}
public function user()
{
return $this->belongsTo('App\User');
}
User Migration
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Product Migration
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('pro_name');
$table->integer('pro_price');
$table->text('pro_info');
$table->integer('stock');
$table->integer('category_id');
$table->string('image')->nullable();
$table->timestamps();
$table->bigInteger('seller_id')->unsigned()->index();
$table->foreign('seller_id')->references('id')->on('users')->onDelete('cascade');
});
}
I would like to see the attributes of the table like price, name, info, img and etc.
Barring the comments about your code, the reason you're not seeing the result of your products query is that you're not passing a closure to the query.
$user = $user->products();
Currently, $user is a QueryBuilder instance. Until you use a closure, like first(), get(), paginate(), etc, you won't be able to see the rows. Modify your code to the following:
$products = $user->products;
// OR
$products = $user->products()->get();
If you omit the (), it will load the relationship using products()->get(), unless already loaded.
Edit: You likely need to include foreign keys to your relationships as the Model name won't match:
User.php
public function products(){
return $this->hasMany(Product_model::class, "seller_id", "id");
}
Probably best to review the contents of the documentation for Relationships; https://laravel.com/docs/5.8/eloquent-relationships. There's a lot of incorrect practices going on with your naming, querying, etc.

Laravel follower/following relationships

I am trying to make a simple follower/following system in laravel, nothing special, just click a button to follow or unfollow, and display the followers or the people following you.
My trouble is I can't figure out how to make the relationships between the models.
These are the migrations:
-User migration:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email');
$table->string('first_name');
$table->string('last_name');
$table->string('password');
$table->string('gender');
$table->date('dob');
$table->rememberToken();
});
-Followers migration:
Schema::create('followers', function (Blueprint $table) {
$table->increments('id');
$table->integer('follower_id')->unsigned();
$table->integer('following_id')->unsigned();
$table->timestamps();
});
}
And here are the models:
-User model:
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts()
{
return $this->hasMany('App\Post');
}
public function followers()
{
return $this->hasMany('App\Followers');
}
}
-And the followers model is basically empty, this is where I got stuck
I tried something like this:
class Followers extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
but it didn't work.
Also, I'd like to ask if you could tell me how to write the "follow" and "display followers/following" functions. I've read every tutorial I could find but to no use. I can't seem to understand.
You need to realize that the "follower" is also a App\User. So you only need one model App\User with these two methods:
// users that are followed by this user
public function following() {
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}
// users that follow this user
public function followers() {
return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}
User $a wants to follow user $b:
$a->following()->attach($b);
User $a wants to stop following user $b:
$a->following()->detach($b);
Get all followers of user $a:
$a_followers = $a->followers()->get();

Laravel one to many relationship results

Hello i am trying to create one to many relationship. One user from user table could have many companies, on other side company could have only one user.
my migration for company table is
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('contact_person');
$table->string('phone');
$table->string('industry');
$table->string('website');
$table->integer('id_user')->unsigned();
$table->foreign('id_user')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
my user model is
/**
* Get the posts for the user.
*/
public function companies()
{
return $this->hasOne('App\Company','user_id');
}
my company model is
public function users()
{
return $this->belongsTo('App\User','id');
}
i am trying to get all companies for specific user
try with whereHas but no data in relation object
$results = Company::whereHas('users', function ($query) {
$query->where('users.id',1);
})->get();
Where is my error?
First thing you should change is companies() relation. It has to be hasMany, not hasOne:
public function companies()
{
return $this->hasMany('App\Company');
}
Then get user with all his companies:
$result = User::where('id', $id)->with('companies')->first();
Or, if you want to use Company model like in your example and get only companies:
$result = Company::where('user_id', $id)->get();
Also, you're using id_user in migration. Change it to user_id.

How to define relation in laravel 5.3 eloquent model?

I have tables in my database schema as follows,
Is it pivot table?
How can I define relationship in eloquent model?
class Role extends Model {
public $timestamps = false;
public function permissions() {
return $this->hasMany('App\Models\RolePermission', 'permissions_id');
}
}
Is this correct way to define relationship? Please help me to understand.
and
class RolePermission extends Model {
public $timestamps = false;
public function role() {
return $this->belongsTo('App\Models\Role', 'roles_id');
}
}
The problem is that you need to name your table permission_role to follow the design pragma.
Role Schema
Schema::create('roles', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Permission schema
Schema::create('permissions', function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Then you just need the permission_role table:
Permission_Role schema
Schema::create('permission_role', function(Blueprint $table){
$table->increments('id');
$table->integer('permission_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->integer('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
Then you just set up your models like this:
class Role {
public function permissions() {
return $this->hasMany(App\Permission::class);
}
}
Then of course your permission class
class Permission {
public function role() {
return $this->belongsToMany(App\Role::class);
}
}
its a many to many relationship bond together by a pivot table Permission_Role. there for each table belongsToMany not hasOne or hasMany
class Role {
public function permissions() {
return $this->belongsToMany(App\Permission::class);
}
}
class Permission {
public function role() {
return $this->belongsToMany(App\Role::class);
}
}

Categories