I have a Many To Many relationshp between User Model & Wallet Model.
So at the User.php Model:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
And at Wallet.php Model:
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id');
}
And also the table Migration of user_wallet table also goes here:
public function up()
{
Schema::create('user_wallet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('usr_id')->on('users');
$table->unsignedBigInteger('wallet_id');
$table->foreign('wallet_id')->references('id')->on('wallets');
$table->integer('balance');
$table->timestamps();
});
}
And at the Controller, I added this:
$bal = Wallet::with("users")->whereHas('users',function ($query)use($wallet_id,$user_id){
$query->where('wallet_id',$wallet_id);
$query->where('user_id',$user_id);
});
dd($bal);
But now I need to update balance filed of this pivot table which has the same user_id and wallet_id:
So how to do this?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
use updateExistingPivot
$wallet = Wallet::find($wallet_id);
$wallet->users()->updateExistingPivot($user_id,["balance"=>500]);
Ref:https://laravel.com/docs/8.x/eloquent-relationships#updating-a-record-on-the-intermediate-table
use something like this:
$bal->users()->sync([
$user_id => [
'balance' => 1
],
]);
Related
I cannot retrieve the username from the foreign key, please help me.
The user table contains a name field I think with the foreign key I could retrieve that. But it does not work.
My migration table
public function up()
{
Schema::create('bookings', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->integer('doctor_id');
$table->unsignedBigInteger('campagne_id');
$table->string('time');
$table->integer('status')->default(0);
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('campagne_id')->references('id')->on('campagne')->onDelete('cascade');
});
}
My booking Model
public function utilisateur()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function Campagne()
{
return $this->belongsTo(Campagne::class, 'campagne_id', 'id');
}
}
my controller
public function liste()
{
$bookings = DB::table('bookings')->paginate(6);
return view('listeAppointement', compact('bookings', 'doctors'));
}
My erreur enter image description here
i dont know happen. Thanks for advance.
Your setup is good to go, Did you verified that all reference 'user_id' from table bookings exist on users table? It happens sometimes when relation not find required field with foreign key.
I'm making a forum with Laravel 8. And I want to return a question and show the name of the user who has asked this question.
At the Model User.php I coded this:
public function questions()
{
return $this->hasMany(Question::class);
}
And also I put this at Question.php Model:
public function users()
{
return $this->belongsTo(User::class);
}
So in order to get the name of a user who has asked the question, I put this:
{{ $show->users->name }}
But now I get this error message:
Trying to get property 'name' of non-object**
So what's going wrong here? How can I fix this issue?
Note that this $show variable comes from this Controller Method and gets the question information:
public function showQuestion($slug)
{
$show = Question::where('slug', $slug)->first();
if(is_null($show)){
abort(404);
}
return view('questions.question',[
'show' => $show
]);
}
And also each question has stored the user_id of the user who has asked this question:
So if you have any idea or suggestion on this, please let me know, I would really appreciate that!
Update #1:
Here is the table users:
Update #2:
questions table migration:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('body');
$table->string('category');
$table->string('private')->nullable();
$table->timestamps();
});
users table migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('phone')->unique();
$table->binary('image')->nullable();
$table->string('job')->nullable();
$table->string('location')->nullable();
$table->string('bio')->nullable();
$table->string('skills')->nullable();
$table->string('stackoverflow')->nullable();
$table->string('github')->nullable();
$table->string('instagram')->nullable();
$table->string('linkedin')->nullable();
$table->string('website')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Your relationship on Question to User should be named user instead of users. When you are letting Eloquent automatically figure out the fields for the belongsTo relationship it actually uses the name of the relationship method to help determine what the foreign key is.
If you don't want to follow that type of convention with naming the method like that you can explicitly set the foreign key used by the belongsTo method:
public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
You have to change the function name users to user in Question model. when you are letting Eloquent automatically figure out the relationship you have to name the function regarding to their relationships like one to one or one to many or many to many.
Try this
public function user()
{
return $this->belongsTo(User::class);
}
{{ $show->user->name }}
Use this for show function in controller
$student= Student::all();
return view('showData',['data' => $student]);
and for view to show data
#foreach($data as $stud)
<tr>
<td>{{$stud)->id}}</td>
<td>{{$stud)->name}}</td>
</tr>
#endforeach
return $this->belongsTo(User::class);
switch to like this, I switched to hasOne and it worked well
return $this->hasOne(User::class, 'id', 'user_id')
->withDefault(['name' => '']);
I'm trying to create a system to log all bookings for a few airbnb hosts, at first I had two models Home and Guest, where a home can have many guests and a guest could book for many homes,
then I thought about creating a guest_home pivot table to link both tables... then things got complicated in my head, what about a Booking model, and (have that booking model act as a pivot table ?) , to me doing new Booking() seemed better than attaching ids to home model?
How could you guys go about this, it's making my brain malt right now...
I thought of doing something like this in my BookingController:
public function createBooking(Request $request)
{
$guestIds = Guest::latest()->take(3)->pluck('id');
$home = Home::findOrFail($request->input('home_id', 2));
$booking = new Booking();
$booking->home_id = $home->id;
$booking->guests()->attach($guestIds);
$booking->save();
return response()->json([
'booking' => $booking,
]);
}
Should I create home_guest pivot table, is a pivot table even needed? what models would I link, please bear with me, so far this is what I got:
Models
class Guest extends Model
{
public function bookings()
{
return $this->belongsToMany('App\Models\Home', 'bookings', 'guest_id', 'home_id');
}
}
class Home extends Model
{
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'bookings', 'home_id', 'guest_id');
}
public function bookings()
{
return $this->hasMany('App\Models\Booking');
}
}
class Booking extends Model
{
//Is Booking needed or I could make a pivot table like home_guest called 'bookings' ?
public function guests()
{
return $this->belongsToMany('App\Models\Guest', 'booking_guest', 'booking_id', 'guest_id');
}
}
Migrations:
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->unsignedInteger('guest_id')->nullable()->index();
$table->foreign('guest_id')->references('id')->on('guests')->onDelete('cascade')->onUpdate('cascade');
$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();
});
Schema::create('guests', function (Blueprint $table) {
$table->increments('id');
$table->string('fullName')->unique();
$table->string('identificationType')->unique();
$table->text('country')->nullable();
$table->timestamps();
});
hi I'm trying to use many to many polymorphic but somehow it doesnt work I attach my code can you find out what I do wrong?
my migration :
Schema::create('stickers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('type');
$table->timestamps();
});
Schema::create('stickables', function (Blueprint $table) {
$table->integer('sticker_id')->nullable();
$table->integer('stickable_id');
$table->string('stickable_type');
$table->primary(['sticker_id', 'stickable_id', 'stickable_type']);
$table->foreign('sticker_id')
->references('id')->on('stickers')
->onDelete('cascade');
$table->timestamps();
});
and my models
Trip model:
public function stickables()
{
return $this->morphToMany(Stickable::class, 'stickable');
}
Stickable model:
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
controller:
public function store(Request $request)
{
$trip = new Trip();
$trip->name = $request->name;
$trip->desc = $request->desc;
$trip->creator_id = Auth::user()->id;
$trip->save();
$tags=$request->tags;
$trip->stickables()->attach($tags);
$trip->save();
return redirect('/trip');
}
Here is how you should define your relationship:
Trip Model:
public function stickers()
{
return $this->morphToMany(Sticker::class, 'stickable');
}
Sticker Model:
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
You don't need a model for your relationship (Stickable).You should create a model for stickers and define your relationship on that.
Stickable can refer to Trip or any other type of model you need to create a relationship with stickers. However in your code you have a stickable method on the Trip model, which does not make sense.
Eloquent Many to Many Polymorphic Relationships
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');