Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What causes the "Column name in where clause is ambiguous" error n this LAtavel 8 app?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading