search in eloquent return query variable - laravel

Here is my problem. Please help
I have these two tables Course and Students. Students take courses. Now I want to get a specific course as shown then see in student table if this course is taken by the student.
Course table:
id
name
description
Student table:
user_id
course_id
semester
address
phone
What I tried:
$course = Course::where('name', '=', $data["id"]);
$enroll= Students::where('course_id', '=', $course["id"]);
$enroll= Students::where('course_id', '=', $course->id);
$$result=$course->toArray();
$enroll= Students::where('course_id', '=', $course["id"]);
I need to search the variable where the return value of eloquent query is stored.

For a specific user and a specific course you can get the collection of records from student table with the following query:
$courceId = 1;
$userId = 1;
$enrolled = Students::where('course_id', $courseId)
->where('user_id', $userId)
->count() > 0;
$enrolled will have true or false value

You can use eloquent relationship to obtain this in a much better way. However you can do this like the following assume your course name is $course_name:
$course = Course::where('name', '=', $course_name)->first();
if($course!=null){
$enroll= Students::where('course_id', '=', $course->id)->get();
}
and then you can check if it has data or not like
if($enroll!=[]){
echo 'this course has been taken by some student';
}
Here some student are the $enroll student.

Related

SQL query similar to the concept of set (complement or except)

I need your help. I just want to display the name of all users (from table users) whose are not in table documents but in today's date
I've tried but I failed
Here is my code
public function activeUser(){
$documents = DB::table('users')
->leftJoin('documents', 'users.id', '=', 'documents.user_id')
->select('users.fname','users.mname','users.sname','documents.created_at')
->where('documents.user_id',null)
->where('documents.created_at',null)
->get();
return view('activity.activity')->with('documents', $documents);
}
I don't know to add current date in the where clause.
The above code gave me the all users who are note in table documents but if user exist in documents once will always considered as is in that documents table.
You can use "whereBetween" (https://laravel.com/docs/6.x/queries#where-clauses).
public function activeUser(){
$yesterday = Carbon::yesterday();
$today = Carbon::today();
$documents = DB::table('users')
->leftJoin('documents', 'users.id', '=', 'documents.user_id')
->select('users.fname','users.mname','users.sname','documents.created_at')
->where('documents.user_id',null)
->whereBetween('documents.created_at', [$yesterday, $today])
->get();
return view('activity.activity')->with('documents', $documents);
}
Remember, you can also use "whereNotInBetween" if that better matches your business logic case.

Laravel Eloquent: orderBy related table

I would like to order result of eloquent by field on the other related table.
I have users table. Every user has one profile. Profile has sponsored (which is boolean) field. So when I would like to get all users, I want to display first sponsored users, then non sponsored.
public function profile(){
return $this->hasOne('App\Doctor');
}
There are two ways:
1)You have to join tables,
User::join('profiles','users.id','=','profile.user_id')->orderBy('sponsored','DESC')->get()
2)Order by eager loading
User::with(array('profile' => function($query) {
$query->orderBy('sponsored', 'DESC');
}))
->get();
Try this one
User::leftJoin('profile', 'user.id', '=', 'profile.user_id')
->orderBy('profile.sponsored', 'ASC')
->get();
I highly recommend not using table joins as it would fail you on the scale.
A better solution is to get users, get their profiles and then sort them using laravel collection methods.
You can use this sample to achieve this solution.
//get all users
$users = User::all();
//extract your users Ids
$userIds = $users->pluck('id')->toArray();
//get all profiles of your user Ids
$profiles = Profile::whereIn('user_id', $userIds)->get()->keyBy('user_id');
//now sort users based on being sponsored or not
$users = $users->sort(function($item1, $item2) use ($profiles) {
if($profiles[$item1->id]->sponsored == 1 && $profiles[$item2->id]->sponsored == 1){
return 0;
}
if($profiles[$item1->id]->sponsored == 1) return 1;
return -1;
});
You can check this link which explains on laravel collection sorts.
$order = 'desc';
$users = User::join('profile', 'users.id', '=', 'profile.id')
->orderBy('profile.id', $order)->select('users.*')->get();

Laravel Query Builder left join

can someone please tell me, why i am not able to select section from sections table using left join. i want list of teachers in a table, i am able to access all data from teachers table, but i am not able to see sections using left join.
Teacher Table have section_id column, which should access data from sections table on section column.
right now it is giving error when i try to fetch data in view using {{$teacher->section}} Below is my code.
public function listteachers(Request $request)
{
$teachers = DB::table('teachers')
->select('teachers.*')
->leftjoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
return view('teachers.list',compact('teachers'));
}
You need to select the columns you want from the sections table in your query.
For example:
$teachers = DB::table('teachers')
->select('teachers.*', DB::raw('sections.name as section_name'))
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();
Change the code to the following
$teachers = DB::table('teachers')
->select('teachers.*','sections.name as section_name')
->leftJoin('sections', 'teachers.section_id', '=', 'sections.id')
->orderBy('pass_exp', 'ASC')
->get();

Finding a user with highest post created in last 24 hours, laravel Eloquent

How to find the user with the highest post created in the last 24 hours in laravel?
sorted by the number of posts in descending order.
If I'm not wrong, you are asking for the users with the highest number of posts created in the last 24 hrs.
To accomplish this, do the following:
$users = User::withCount(['posts' => function ($query) {
$query->where('created_at', '>=', carbon()->now()->subDay());
}])->orderBy('posts_count', 'DESC')
->get();
As the documentation states, you can add constraints to the queries.
Counting Related Models
If you want to count the number of results from a relationship without actually loading them you may use the
withCount method, which will place a {relation}_count column on
your resulting models. For example:
$posts = App\Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
You may add the "counts" for multiple relations as well as add
constraints to the queries:
$posts = Post::withCount(['votes', 'comments' => function ($query) {
$query->where('content', 'like', 'foo%');
}])->get();
echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
use Carbon\Carbon;
get user id:
$minusday = Carbon::now()->subDay();
$user_id = DB::table('posts')
->select('user_id', DB::raw('count(id) as total'))
->where('created_at', '>=', $minusday)
->groupBy('user_id')
->orderBy('total','desc')
->limit(1)
->get();
In regular SQL syntax you'd need something like below:
SELECT COUNT(id), user_id
FROM posts
WHERE created_at = today
GROUP BY user_id
ORDER BY COUNT(user_id) DESC
LIMIT 1;
It gets all the posts, groups them by user_id, sorts them with the highest user_id count up top and gets the first record.
I am by no means an expert on SQL, let alone the query builder in Laravel, so someone else would probably be better at writing that.
I know that you can get the posts that were created today by using Carbon, like so:
Post::whereDate('created_at', Carbon::today())->get();
EDIT: This might work for you:
$last24h = Carbon::now()->subDay();
DB::table('posts')
->select(array(DB::raw('COUNT(id)', 'user_id')))
->where('created_at', '>=', $last24h)
->groupBy('user_id')
->orderBy('COUNT(id)', 'DESC')
->limit(1)
->get();
Be sure to include use Carbon\Carbon to be able to use Carbon.
This should give you both the amount of posts and the corresponding user id.

Laravel 4/5, order by a foreign column

In Laravel 4/5 how can order a table results based in a field that are connected to this table by a relationship?
My case:
I have the users that only store the e-mail and password fields. But I have an another table called details that store the name, birthday, etc...
How can I get the users table results ordering by the details.name?
P.S.: Since users is a central table that have many others relations and have many items, I can't just make a inverse search like Details::...
I would recommend using join. (Models should be named in the singular form; User; Detail)
$users = User::join('details', 'users.id', '=', 'details.user_id') //'details' and 'users' is the table name; not the model name
->orderBy('details.name', 'asc')
->get();
If you use this query many times, you could save it in a scope in the Model.
class User extends \Eloquent {
public function scopeUserDetails($query) {
return $query->join('details', 'users.id', '=', 'details.user_id')
}
}
Then call the query from your controller.
$users = User::userDetails()->orderBy('details.name', 'asc')->get();

Resources