Alex Al
Alex Al

Reputation: 156

How to switch code from db class to Eloquent query? Laravel

I want from the DB class to switch to Eloquent and I have a few of queries

This is first, I want to insert in subscription_user user_id of user and hard core subscription_id = 1 as default.

    DB::table('subscription_user')->insert(
            ['user_id' => $user->id, 'subscription_id' => 1]
        );

Second, I want to return verification token

     $check = DB::table('user_verifications')->where('token', 
     $verification_code)->first();

Third, I want to update accepted field

       $res =   DB::table('offers')
        ->where('id', $id)
        ->update(['accepted' => 1]);

Upvotes: 1

Views: 109

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14271

#1

DB::table('subscription_user')->insert(
        ['user_id' => $user->id, 'subscription_id' => 1]
    );

Eloquent equivalent (*):

$subscriptionUser = SubscriptionUser
                        ::create(['user_id' => $user->id, 'subscription_id' => 1]);

In case this comes from a many-to-many relationship between the models Subscription and User you could just do (**):

Subscription::find(1)->users()->attach($user->id);

#2

$check = DB::table('user_verifications')->where('token', 
$verification_code)->first();

Eloquent equivalent (***):

$check = UserVerification::where('token', $verification_code)->first();

#3

$res = DB::table('offers')
    ->where('id', $id)
    ->update(['accepted' => 1]);

Eloquent equivalent:

$res = Offer::find($id)->update(['accepted' => 1]); // this will return a boolean.
$offer = Offer::find($id); // this will get the updated record.

(*) In order for this to work you need a Eloquent model called SubscriptionUser with the table property set to: 'subscription_user'.

(**) In order for this to work you need to set the relationship in the models.

(***) In order for this to work you need a Eloquent model called UserVerification with the table property set to: 'user_verifications'.

Upvotes: 2

Related Questions