How do I query two related models in Laravel - laravel-5

I'm stuck on a Laravel blog project I'm working on. I have 2 related models, User and Post, and then in my blade file a search form which will query both models for result. In my Controller method, I have:
$q = $request->keyword;
$results = Post::where ('title', 'LIKE', '%{$q}%')->orWhere('body', 'LIKE', '%{$q}%')->with(['user' => function($x){
$x->orWhere('name', 'LIKE', '%{$q}%')->get();
}])->get();
return view('result')->withResults($results);
Issue is I don't get a response in my blade file. I suspect there's a bug in my controller method but I just can't wrap my head around it. I am using Laravel 5.4.

Related

Laravel Eloquent - orWhereHas method - When to use it and how

I'm trying to understand some advanced eloquent commands and on the Laravel official documentation, there is not so much about the Eloquent orWhereHas method and there isn't also an example about how it works.
https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Can somebody help me to understand it with also a simple example?
How to use it: just chain as any other Eloquent method
User::whereHas(...)->orWhereHas(...)->get();
When to use it: imagine you have Users, Posts and Comments, and each user can write posts and comments. Then you need to get active users. For example, you assume active as user, who has made posts OR comments last 7 days. So, you can get it this way:
$users = App\Models\User::query()
->whereHas('posts', function (Builder $query) {
$query->where('created_at', '>=', Carbon::now()->subDays(7));
})
->orWhereHas('comments', function (Builder $query) {
$query->where('created_at', '>=', Carbon::now()->subDays(7));
})
->get();
Say there's a blog kind of app. The main entity/model of the app would be Post (Blog Post).
When any author writes and publishes a Post,
visitors to the blog site can leave Comment(s) for the Post
visitors can Like a Post
So we have 3 models here
Post - which can have many Comment(s)
Post - can have many Like(s)
Now let's say for some reason we want to get all Post records from the database which either have 10 or more comments in the current month or 3 or more likes in the current month
We can write a query like
$posts = Post::whereHas('comments', function($query) {
$query->where('created_at', '>', now()->startOfMonth();
}, '>=', 10)
->orWhereHas('likes', function($query){
$query->where('created_at', '> ', now()->startOfMonth();
}, '>=', 3)
->get();
Laravel docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Just like where both whereHas and orWhereHas accepts closure as 2nd argument for more fine grained query control.
Actually whereHas is supposed to be used when you want to have more power on constraints.
If you just want to check the existence of relation records you can use has for eg:
Get all post records which either have comment or like and paginate 20 per page
$postsWithCommentsOrLikes = Post::has('comments')
->orHas('likes')
->paginate(20);

How to add paginate to laravel eloquent?

I am new to laravel and I am having error in adding paginate using laravel eloquent.
This code work without paginate(). If paginate was added, got error
Method paginate does not exist.
$articles = Article::orderBy('updated_at', 'DESC')
->findOrFail([1,2,3,4,5])
->where('status','p')
->paginate(7);
As people have mentioned in the comments, you can not use findOrFail() with paginate() since they are both ways to execute a query. You can instead use whereIn().
To get what you're after you can do:
$articles = Article::orderBy('updated_at', 'DESC')
->whereIn('id', [1,2,3,4,5]) //assuming "id" is the primary key for the table
->where('status','p')
->paginate(7);

Form Model Binding with relationship

I already looked at this post but I can't seem to make it right:
Laravel form model binding
I get this error:
https://gyazo.com/2ea7b7bb6a19d588829447ee1a92053e I use laravel 5.2
for this.
some screenshots:
https://gyazo.com/1b2c35e660dfe1aae69a02703733d083
https://gyazo.com/3d6f294473f6e54650a4a4403dc2777e
https://gyazo.com/a59aebc7362f51f9ac27852ea032f962
To expand on my comment:
Your problem is here:
$user = User::where('id', $id) // Here more specifically, Laravel does not know if you mean id of users table or details table
->leftJoin('user_details', user_details.user_id', '=', 'users.id')
->first();
Rewrite your where statement like this:
$user = User::where('users.id', $id)....
And it should work. Basically since you're joining 2 tables and they both got id you need to specify which id you want to query by.

Laravel 5.3 Eager Loading Selected Fields

I have this code:
$products = \App\Product::whereIn('id', $arrayKeys)
->with('photo')
->get();
And the result is:
If I use select code like this one:
$products = \App\Product::whereIn('id', $arrayKeys)
->select(['desc'])
->with('photo')
->get();
I can't see the photo. Is there a way to it? So that I can get the selected fields as well as the photo relationship.

Datatable server-side using Eloquent with laravel

im using bllim-datatables package for laravel server side and i don't understand how to do if, for example, i want to display only posts from user = 2 with eloquent.
$posts = Post::select(array('posts.id','posts.name','posts.created_at','posts.status'));
return Datatables::of($posts)
->filter_column('id', 'where', 'User.id', '=', '2')
->make();
I know this is not gonna work but can someone explain to me the correct way, please ?

Resources