Laravel
Laravel Union throws an error unless the number of columns matches the original table
Table Of Contents
I wrote an article on how Laravel Union throws an error unless the number of columns matches the original table.
PR
What kind of error occurs
SQLSTATE[21000]: Cardinality violation: 1222 The used SELECT statements have a different number of columns (SQL: (select `title`, `created_at` from `posts` where `title` is not null) union (select `title` from `items`))You will get this error.
How to resolve
The error message says, "The used SELECT statements have a different number of columns."
Therefore, I think this error can be resolved by selecting the same number of columns.
use App\Models\Item;
use App\Models\Post;
~~~
public function index()
{
$items = Item::select('title','created_at');
$results = Post::select('title','created_at')
->union($items)
->get();
dd($results);
}Summary
That's it.
I wrote an article about the error that occurred when using Union in Laravel.
I hope this can be helpful to someone.
That's all!
Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!




