Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rretzko's avatar

Error when using concat() in query: "syntax error, unexpected token "as", expecting ")"

Hi all - I'm trying to use the following query in a Livewire v3 method but am getting the error: "syntax error, unexpected token "as", expecting ")". Here's the query:

Member::query()
            ->join('students', 'students.id', '=', 'ensemble_members.student_id')
            ->join('users', 'users.id', '=', 'students.user_id')
            ->where('ensemble_id', $this->form->ensembleId)
            ->where('school_year', $this->program->school_year)
            ->select('ensemble_members.*',
                'users.name', 'users.last_name', 'users.first_name',
                concat('users.name', ' (', 'students.id', ')') AS 'studentData'
            )
            ->orderBy('users.last_name')
            ->orderBy('users.first_name')
            ->get()
            ->toArray();

The query works as expected without the concat function, but I can't see where I've erred. Thanks for the help!

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

The error comes from how you're using the concat function in your Eloquent query. In Laravel's query builder, you can't use PHP's concat() function directly in the select clause. Instead, you need to use a raw expression with DB::raw() and proper SQL syntax.

Here's how you can fix your query:

use Illuminate\Support\Facades\DB;

Member::query()
    ->join('students', 'students.id', '=', 'ensemble_members.student_id')
    ->join('users', 'users.id', '=', 'students.user_id')
    ->where('ensemble_id', $this->form->ensembleId)
    ->where('school_year', $this->program->school_year)
    ->select(
        'ensemble_members.*',
        'users.name',
        'users.last_name',
        'users.first_name',
        DB::raw("CONCAT(users.name, ' (', students.id, ')') AS studentData")
    )
    ->orderBy('users.last_name')
    ->orderBy('users.first_name')
    ->get()
    ->toArray();

Key Points:

  • Use DB::raw() to write raw SQL expressions.
  • The SQL CONCAT() function is used inside the raw expression.
  • The alias (AS studentData) should be inside the string passed to DB::raw().

This should resolve the syntax error and return the desired concatenated value as studentData.

Please or to participate in this conversation.