I have a One To Many relationship between User Model & Order Model:
User.php:
public function order()
{
return $this->hasMany(Order::class);
}
Order.php:
public function user()
{
return $this->belongsTo(User::class);
}
Now I need to access user instance from order:
$order = Order::where('id', $id)->update(['status' => 'verified', 'price' => $data['price']]);
$user = $order->user;
dd($user);
But in this way, I get this error:
Trying to get property 'user' of non-object
So how to solve this issue and access user instance properly?
Here is the Migration of orders table:
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('material');
$table->string('color');
$table->string('dimensions');
$table->string('description')->nullable();
$table->tinyInteger('user_id')->unsigned()->nullable();
$table->timestamps();
});
update method wont return order detail's because update return true or false. So change it to
$order = Order::find($id);
$order->status='verified';
$order->price=$data['price'];
$order->save();
$user = $order->user;
update method takes array as argument update(array $values) and return int
Why don`t you add in the migration the relation as a foreignID?
$table->foreignID('user_id')->constrained();
Related
I'm trying to make an app where airbnb hosts can have a log of their bookings, I created three models: Home, Guest and Booking. Booking being the main player, I also think there should be a pivot table but I'm not sure which models should it link... I decided to go with booking_guest but I'm getting the following error when I create a booking:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'booking_id' cannot be null (SQL: insert into `booking_guest` (`booking_id`, `guest_id`) values (?, 1), (?, 2))
I do something like this in my BookingController:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = new Booking();
$booking->home_id = $home->id;
$booking->guests()->attach($guestIds);
$booking->save();
return response()->json([
'booking' => $booking,
]);
}
I'm not feeling too sure about this configuration, could you guys share some light on me.
These are my models:
class Home extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'guest_home', 'home_id', 'guest_id');
}
public function bookings()
{
return $this->hasMany('App\Models\Booking');
}
}
class Booking extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
}
}
class Guest extends Model
{
public function bookings()
{
return $this->belongsToMany('App\Models\Booking', 'booking_guest', 'guest_id', 'booking_id');
}
}
My migrations:
//Booking guest pivot table
Schema::create('booking_guest', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('booking_id')->index();
$table->foreign('booking_id')->references('id')->on('bookings')->onDelete('cascade')->onUpdate('cascade');
$table->unsignedInteger('guest_id')->nullable()->index();
$table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Schema::create('guests', function (Blueprint $table) {
$table->increments('id');
$table->string('fullName');
$table->text('country');
$table->timestamps();
});
Schema::create('bookings', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('home_id')->index();
$table->foreign('home_id')->references('id')->on('homes')->onDelete('cascade')->onUpdate('cascade');
$table->timestamp('entryDate')->nullable();
$table->timestamp('exitDate')->nullable();
$table->timestamps();
});
Schema::create('homes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('host_id')->index();
$table->foreign('host_id')->references('id')->on('hosts')->onDelete('cascade')->onUpdate('cascade');
$table->string('fullAddress')->unique();
$table->integer('rooms')->unique();
$table->timestamps();
});
As you can see from here:
public function create(Request $request)
{
...
$booking = new Booking(); // <-- here
$booking->guests()->attach($guestIds); // <-- here
$booking->save(); // <-- here
...
}
you are creating a new instance of Booking, then associating to it a Guest and then saving the instance of Booking.
However ->attach(...) tries to associate the Booking with the Guest, but the Booking does not exists at that time on the DB.
I would suggest to use Booking::create, so that after that statement, the booking exists on the DB and so you can attach to it the Guest:
public function create(Request $request)
{
$guestIds = Guest::latest()->take(2)->pluck('id');
$home = Home::findOrFail(1);
$booking = Booking::create([ // <- using Booking::create
'home_id' => $home->id // <- using Booking::create
]); // <- using Booking::create
$booking->guests()->attach($guestIds);
return response()->json([
'booking' => $booking,
]);
}
I am making FollowController where I have two tables following_users table and following_user_item table. which is in hasMany relationship. When a authenticate current_user wants to follow an user, the ID of the user will stored in following_users table and its relational table stored the current_user_id and the following_user_id (which is the id of following_users table). here is the schema.
following_users_table:
public function up()
{
Schema::create('following_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users');
$table->timestamps();
});
}
following_user_item_table:
public function up()
{
Schema::create('following_user_items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('following_users_id')->unsigned();
$table->foreign('following_users_id')
->references('id')
->on('following_users');
$table->bigInteger('user_id')->unsigned();
$table->timestamps();
});
}
I have done the FollowController but the problem is comming when try to check whether the user is already followed or not.
Follow Relationship in User model
public function followingUserList()
{
return $this->hasOne('App\FollowingUser');
}
/**
* Get the stories associated with the user through an intermediate table
*
*/
public function followingUsers()
{
return $this->hasManyThrough(
'App\FollowingUserItem',
'App\FollowingUser',
null,
'following_users_id'
);
}
FollowingUser Model Relationship with User and FollowingUserItem
public function user()
{
return $this->belongsTo('App\User');
}
public function users()
{
return $this->hasMany('App\FollowingUserItem','following_users_id');
}
Here is my FollowController:
class FollowController extends Controller
{
//
public function index($id)
{
$user = User::find($id);
$logged_userId = Auth::User();
if ($user->id == $logged_userId->id) {
return [
'status' => false,
'message' => 'You can not Follow yourself',
];
}
if ($user && $logged_userId) {
$checkUsers = FollowingUser::where('user_id', $user->id)->get()->users()->where('user_id', $logged_userId->id);
if ($checkUsers)
{
return 'already followed';
}
else
{
$user->followingUserList()->save(new FollowingUser())->users()->save(new FollowingUserItem(['user_id' => $logged_userId->id]));
return 'sucess';
}
}
}
}
I go the error
Method Illuminate\Database\Eloquent\Collection::users does not exist.
When you call get() Laravel returns a collection as it does not know how many rows there will be there. This is why you get collection does not have users set error. Since you filter on an id you know there is only gonna be one, therefor you can utilize the first() method.
So change the code to use first().
$checkUsers = FollowingUser::where('user_id', $user->id)->first()->users()->where('user_id', $logged_userId->id);
I have a blog built with laravel.
and I want to add likes to my posts.
so I created a Like model with a likes table.
this is what i have done in my Like model
public function post(){
return $this->belongsTo(Post::class);
}
public function user(){
return $this->belongsTo(User::class);
}
in my Post and User models
public function likes(){
return $this->hasMany(Like::class);
}
and my migration file for likes table
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->boolean('value');
$table->timestamps();
});
I want to set the values in my controller on this way!
public function liker($postID, $userID, $value){
$like = new Like([
'post_id' => $postID,
'user_id' => $userID,
'value' => $value
]);
$like->save();
return redirect()->back();
}
but the view return 419 error page. (Page Expired)
and also no changes (no row) adds to my database(likes table)!
can you help me?
you dont need value on a like, if it exists, it's a "like" and you should use is as a pivot table (you already have 2 foreign IDs in it)
Schema::create('likes', function (Blueprint $table) {
$table->unsignedInteger('post_id');
$table->unsignedInteger('user_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->tinyInteger('is_dislike')->default(0);
$table->timestamps();
});
then declare the relation between Post and User
Post
public function votedUsers(){ //or simply likes
return $this->belongsToMany(User::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}
User
public function votedPosts(){
return $this->belongsToMany(Post::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}
Next to create a like just do it like this
public function liker($postId, $userId, $value){
$user = User::findOrFail($userId); //or use auth()->user(); if it's the authenticated user
$user->votedPosts()->attach($postId);
return redirect()->back();
}
to Remove a like use detach($postId) instead.
For dislike
$user->votedPosts()->attach($postId, ['is_dislike' => 1]);
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.
I'm trying to make a many to many relation, in this example with user and role.
In User model I got this:
public function roles()
{
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}
In Role model I got this:
public function users()
{
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id');
}
And my pivot table user_role:
public function up()
{
Schema::create('user_role', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles');
$table->foreign('user_id')->references('id')->on('users');
});
}
Now when I do $user->roles()->attach(1); it makes a row in the user_role table. But the problem is when I want to access it: $user->roles; it returns nothing. It works with $role->users; but not the other way. What am I doing wrong?
Solved : Laravel 5.2.29
make sure the table name is role_user
$user = User::find(1);
$role = Role::find(2);
// In this example I am passing in a Role object but $role->id also works
$user->roles()->attach($role);
Hope this works for you.
You have to reload the relationship after attaching like so
$user->roles()->attach($role);
$user->load('roles');