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

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]);

#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'.

Related

Laravel - How to sort an array of objects in ascending order by ID

I need to sort an array of objects in ascending order by ID called $messages, I tried many things but none seem to be working. Here is what I tried:
public function getMessagesPage(Request $request)
{
$user_id = $request->session()->get('id');
$user_second = User::where('username', $request->username)->first();
$messages_1 = Messages::where('user_1', $user_id, 'AND')->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
$messages_2 = Messages::where('user_2', $user_id, 'AND')->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();
$messages = $messages_1->merge($messages_2);
$messages = collect($messages);
$messages->sortBy('id');
return view('messages')->with('messages', $messages)->with('user_id', $user_id)->with('user_second', $user_second);
}
You can sort your collection with sortBy() but remember that the function returns the collection sorted, doesn't mutate the original collection, so you have to change this line:
//$messages->sortBy('id');
$messages = $messages->sortBy('id');
As better alternative you can get all the messages sorted with only one query:
$messages = Messages::where([['user_1', $user_id], ['user_2', $user_second->id]])
->orWhere([['user_2', $user_id], ['user_1', $user_second->id]])
->orderBy('id', 'asc')
->get()
This is the same as writing this SQL:
select * from messages
where (user_1 = $user_id and user_2 = $user_second->id)
or (user_2 = $user_id and user_1 = $user_second->id)
order by id asc
You could try
$messages_1 = Messages::where('user_1', $user_id)->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
$messages_2 = Messages::where('user_2', $user_id)->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();
Remove the AND from the first WHERE. Eloquent knows that if you chain ->where() clauses, to use AND between them.
Alternatively, if you are using Laravel 5.3 or greater you can pass an array to in a where clause
$messages_1 = Messages::where([
'user_1' => $user_id,
'user_2' => $user_second->id])
->orderBy('id', 'asc')
->get();
Alternatively, if the following $messages = collect($messages); is correctly returning a Key / Value pair array, you should simply be able to use the following
return view('messages')
->with([
'messages' => sort($messages),
'user_id' => $user_id,
'user_second' => $user_second
]);

Laravel has on where function

I'm currently using this function to gather all of my users with a relationship
$users = users::with(array('statusCurrent' => function($query)
{
$query->where('status.status', 'in');
$query->orderBy('status.date', 'DESC');
}));
$users = $users->get();
This returns both of my users, and if status = 'in' then it returns the relationship aswell, but if status = 'out' it still returns the row, but with status_current = null.
Basically I want to ignore the user completely if the arguments inside the with query builder function are not true.
I have tried $candidates = $candidates->has('statusCurrent')->get(); to try and only get results where the relationship is not null, but it still returns users where the StatusCurrent relationship is null.
How do I do it so that foreach of the users, if whatever arguments I pass into the with(array('statusCurrent' => function(){}) are not true, it is ignored completely?
EDIT
Users Model
public function statusCurrent(){
return $this->hasOne('App\Status', 'user_id', 'id')->orderBy('date', 'desc')->limit(1);
}
The user can have many status', but the StatusCurrent relationship is meant to return their 1 most recent status based on the status.date
You need whereHas to filter out users based on their relationship
$users = users::with(array('statusCurrent' => function($query)
{
$query->orderBy('status.date', 'DESC');
}))
->whereHas('statusCurrent', function ($query) {
$query->where('status', 'in');
})
->get();
See Querying Relationship Existence

Laravel Eloquent - Filter is ignored when returning results

I am trying to return a (JSON) string of a specific user with his/her posts. However the Post model contains several columns that aren't of interest for API implementations and I want to exclude these columns from the result.
Why does the following still return no columns at all in the Posts relation
I've tried multiple ways of retrieving specific columns on the Post model.
$result = User::with([
'posts' => function($q) {
$q->addSelect('title', 'tag');
}])
->where(['api' => 1, 'id' => $id])
->first(['id', 'username', 'role']);
return $result;
dumping
$q->get()
shows exactly what I want, however the returned $result includes none of the columns in the Post model.
My Laravel version is 5.2
try changing addSelect to just select
$result = User::with([
'posts' => function($q) {
$q->select(['title', 'tag', 'user_id']); // You might have to also include `user_id` here
}])
// ->where(['api' => 1, 'id' => $id]) change this
->where('api', 1)
->where('id', $id)
->first();
return $result;
Because addSelect is adding items to an existing select, rather than specifying what you actually want in the select.

Retrieve multiple record from database in Laravel 5.2

I want to check if user login only if email exist and activated==1
set in database but activated always show null value.
Image 1:
Image 2:
Try this one
$user = DB::table('users')->where([
['email', '=', $email],
['activated', '=', '1'],
])->get();
or
make your where clause with array to check multiple conditions.
You can use Model class to get data using where clause.
See Queries: Laravel
Another Example (eloquent):
$matchThese = ['email' => $email, 'activated' => '1'];
//........
//........
$results = User::where($matchThese)->get();

Laravel Create OR update related model

I have the following function to create a new related model;
//Create the results entry
$result = new Result([
'result' => $total,
'user_id' => $user->id,
]);
//attach it to the fixture - parse through looking for the user_id or opponent_id
//to match the current user in the loop.
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
$fixture->results()->save($result);
The ->save() at the end does most of the magic, attaching the correct fixture_id to the result table. The problem is that if the function is run again, it creates new entries for the same results.
There is a firstOrCreate() method, but i don't know how to use this when saving a related model.
Thanks
It's exactly like this: http://laravel.com/docs/5.0/eloquent#insert-update-delete.
//Create or find a existing one...
$result = Result::firstOrCreate([
'result' => $total,
'user_id' => $user->id,
]);
//grab fixture...
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
//associate (set fixture_id in $result equals to $fixture's key)
//any previous association will disappear.
$fixture->results()->associate($result);
//save to write changes in the database.
$result->save()
you can check here (https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L559). Laravel will search in your database and return if it found it or create a new.

Categories