Laravel Query Builder with CONCAT and DATE_FORMAT giving errorr - laravel

I have a query like below:
$events = Event::select(DB::raw('CONCAT(title," : 📅", DATE_FORMAT(date,"%M %d %Y") AS event'), 'id')->where('club_id', '=', \Auth::guard('web_club')->user()->id)->where('date','>',date("Y-m-d",strtotime("-2days")))->orderBy('date','asc')->pluck('event', 'id');
I am trying to format the datetime into a more legible format but keep getting the error:
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'from `events` where `club_id` = ? and `date` > ? order by `date` asc' at line 1 (SQL: select CONCAT(title," : ", (DATE_FORMAT(date,"%M %d %Y")) AS event, `id` from `events` where `club_id` = 75 and `date` > 2020-03-13 order by `date` asc) "
Can anyone see what I am doing wrong at all or alternative methods to achieve the same result?

I was missing a bracket near here which was responsible for the error.
DATE_FORMAT(date,"%M %d %Y"))

Related

Laravel Group data by Month Query works with MySQL but Fails on PostgreSQL database

I'm trying to group data by month for the current year. The query below works on MySQL database but gives an error when connected to PostgreSQL.
$results = DB::table('visits')
->select(DB::raw('month(visitdate) month, count(*) data'))
->where('team_id', 2)
->whereYear('visitdate', now()->year)
->groupBy('month')
->get();
This error was generated:
SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "month" LINE 1: select month(visitdate) month, count() data from "visits" w... ^ (SQL: select month(visitdate) month, count() data from "visits" where "team_id" = 2 and extract(year from "visitdate") = 2021 group by "month")
I tried a similar query with Eloquent and got the same results.
The visitdate column stores the date in the format "2021-01-01"
I'm using laravel 8 with Breeze
month is a keyword. You should choose something else instead, or put it in double quotes, or in this case just put AS in front of it. Any of the three should work.

Query on a view ,Postgres and Laravel

I try to do a query on a view from DB, with Laravel but I get an error, and I am not sure why.
ViewData::query()->where('page', '=', '918');
"SQLSTATE[42601]: Syntax error: 7 ERROR: zero-length delimited
identifier at or near """"↵LINE 1: ...data" where "page" = $1 order by
"view_full_data"."" asc lim...↵
^ (SQL: select * from "view_full_data" where "page" = 918 order by
"view_full_data"."" asc limit 1000 offset 0)"
From Postgres, a working one.
Select * from view_full_data where "page = 918;
I found the problem.
From Maatwebsite\Excel I get an order_by that is not ok (Maybe because I don't have an ID column).
I had to add orderBy manually.
ViewData::query()->where("page", '=', "918")->orderBy('page', 'asc');

in sql the following query is given my desired output but in laravel model how can I retrieve it?

sql query is
select *,sum(diposit_amount) as total from `diposits` group by `member_id`;
I am trying in model like this way
App\diposit::groupBy('member_id')
->selectRaw('*,sum(diposit_amount) as total')
->get();
but it gives errors "SQLSTATE[42000]: Syntax error or access violation: 1055 'pos.diposits.id' isn't in GROUP BY (SQL: select *,sum(diposit_amount) as total from diposits group by member_id) (View: C:\xampp\htdocs\pos\resources\views\welcome.blade.php) "

Laravel query builder how to write orderBy query having CAST and REPLACE functions

i have a query like this
SELECT area FROM history_cost_estimation ORDER BY CAST(REPLACE(area, ' ', '') AS INT)
i'm trying to translate such query into laravel query builder but i got many errors
this is my try
App\Models\HistoryCostEstimation::orderBy("CAST(REPLACE(area, ' ', '') AS INT)",'asc')->count();
and here is sample of the error
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'as `)` asc' at line 1 (SQL: select count(*) as aggregate from `engineertec`.`history_cost_estimation` order by `CAST(REPLACE(area,` as `)` asc)
I would use the DB facade and use raw mysql
make sure to add the DB facade to the controller or wherever you are running this
use Illuminate\Support\Facades\DB;
then do
DB::table('history_cost_estimation')->select('area')->orderBy(DB::raw('CAST(REPLACE(area, ' ', ''), 'INT')));

Using a helper function to change a field of a query in Laravel 4 using DB:raw

I have a query function that I am using to pull some data from my database. I also have a function that changes around the "created_at" field to print it like so: Month Day YY'
Here is the query function:
public static function friend_activity_json($start = 0, $number_of_posts = 2) {
$friend_activity = DB::table('fanartists')
->join('fans', 'fanartists.fan_id', '=', 'fans.id')
->join('artists', 'fanartists.artist_id', '=', 'artists.id')
->orderBy('fanartists.created_at', 'DESC')
->select(DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name'))
->get();
The function is in the folder helpers, in a filed called "StringEdit.php". The function is getDate:
public static function getDate($date) {
$full_date = explode(" ", $date);
$date_pieces = explode("-", $full_date[0]);
$year = substr($date_pieces[0], -2);
$monthNum = $date_pieces[1];
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
$final_date = $monthName ." ". $date_pieces[2] ." '".$year;
return $final_date;
}
I have been able to call this function elsewhere, so I know it works. How do I get it to work in this context to change around my "created_at" field? When running this I get the error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans' at line 1 (SQL: select StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
EDIT: New Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gende' at line 1 (SQL: select DATE_FORMAT(fanartists.created_at, "%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
This won't work like the way you used it in your query here
DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name')
Here, getDate function is being treated as mysql function and it's not valid, anyways, you can use mysql's native DATE_FORMAT function instead, like
DATE_FORMAT(fanartists.created_at, "%M %d %y") as created_at
Check the documentation.

Resources