I am working on a Laravel 8 app with users and posts.
I want to display the full name of the author on each post (article).
For this purpose, in the PostsContoller, I have:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\users;
class PostsContoller extends Controller {
public function index(Request $request){
$viewData = $this->loadViewData();
$viewData['page_title'] = "Posts";
$viewData['posts'] = $this->posts($request);
return view('posts', $viewData);
}
public function posts(Request $request) {
$query = $request->input('query');
return Invoice::select (
"posts.id",
"posts.name",
"posts.description",
"posts.content",
"user.name as first_name",
"user.surname as last_name",
)
->leftJoin("posts", "posts.user_id", "=", "users.id")
->where('name', 'like', '%' . $query . '%')
->orWhere('description', 'like', '%' . $query . '%')
->orWhere('content', 'like', '%' . $query . '%')
->orWhere('first_name', 'like', '%' . $query . '%')
->orWhere('last_name', 'like', '%' . $query . '%')
->orderBy('posts.id','ASC')
->paginate(10);
}
}
The problem
Laravel throws this error:
Column 'name' in where clause is ambiguous
Where is my mistake?
>Solution :
The error message is pretty clear, your where clauses references a column name that exists in more than one of the tables you are working with in your query:
->where(‘name’, ‘like’, ‘%’ . $query . ‘%’)
So you need to make the where clause more specific. Are you referring to name on posts or user?
As you want to reference the posts table, you will want to specify that as part of your where clause:
->where('posts.name', 'like', '%' . $query . '%')
Note that you will need to do the same for any other columns in your statement that might have column names present in other tables.