Laravel having column name in where clause static method

Related searches

Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case


$user = User::whereName('john')->first(); // added `name` as a column name

When called this code to SQL it generates

$user = User::whereName('john')->toSql();

//it returns
select * from `users` where `name` = ?

This indeed gives expected result as it returns a user with name john.

I have searched Laravel documentation but can't find this function or where it was defined.

All I need is clarification if this method is good or best so that I can continue using it and as well know how the method is generated inside Laravel framework or any other means

If you're asking where is the code responsible for it to work, it's using the magic method __call() (__callStatic() before that to make an instance) in the class Illuminate\Database\Query\Builder

     * Handle dynamic method calls into the method.
     * @param  string  $method
     * @param  array   $parameters
     * @return mixed
     * @throws \BadMethodCallException
    public function __call($method, $parameters)
        if (static::hasMacro($method)) {
            return $this->macroCall($method, $parameters);

        if (Str::startsWith($method, 'where')) {
            return $this->dynamicWhere($method, $parameters);


precisely in the condition Str::startsWith($method, 'where') which redirect the call to dynamicWhere()

     * Handles dynamic "where" clauses to the query.
     * @param  string  $method
     * @param  array  $parameters
     * @return $this
    public function dynamicWhere($method, $parameters)
        $finder = substr($method, 5);

        $segments = preg_split(
            '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE

        // The connector variable will determine which connector will be used for the
        // query condition. We will change it as we come across new boolean values
        // in the dynamic method strings, which could contain a number of these.
        $connector = 'and';

        $index = 0;

        foreach ($segments as $segment) {
            // If the segment is not a boolean connector, we can assume it is a column's name
            // and we will add it to the query as a new constraint as a where clause, then
            // we can keep iterating through the dynamic method string's segments again.
            if ($segment !== 'And' && $segment !== 'Or') {
                $this->addDynamic($segment, $connector, $parameters, $index);


            // Otherwise, we will store the connector so we know how the next where clause we
            // find in the query should be connected to the previous ones, meaning we will
            // have the proper boolean connector to connect the next where clause found.
            else {
                $connector = $segment;

        return $this;

Laravel having column name in where clause static method , Recently I just realized that Laravel generates a static method with column name when joined in a where clause using camel case. example Laravel isn't using a static method, you are. Another way to do this which you are probably looking for is to use dependency injection, which Laravel makes very easy because it can be done automatically.

This approach is completely legit, thou not well documented. In Query\Builder it utilize the __call function overwrite to produce the functionality and you can see the exact function here.

The subject of magic methods and the __call function, is often highly debatable if they are for the better. If you utilize IDE helper. It will actually type hint the methods for you and therefor alleviate some of the magical approaches it takes and provide you with a smooth IDE experience.

An example of the generated type hints from a local project i have.

* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\User whereEmail($value)

Therefor i would not be worried that this is not the best approach. There are many ways of doing what you are doing, but this one is one of the correct ones.

Column names as parameter � Issue #1891 � laravel/ideas � GitHub, The bellow method validate DB table columns and return a string which can be reused as a column name parameter for a select query. @param $tableName string() * @param $columns array() * @return mixed */ public static function For one, the query cache would have problems unless the php code� {note} PDO does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns, etc. If you must allow the user to select certain columns to query against, always validate the column names against a white-list of allowed columns. Retrieving Results

Try This

$user = User::where('name','john')->first();

Database: Query Builder - Laravel, Therefore, you should never allow user input to dictate the column names methods may be used to set a raw string as the value of the having clause. I'm using the Laravel Eloquent query builder and I have a query where I want a WHERE clause on multiple conditions. It works, but it's not elegant. It works, but it's not elegant. Example:

you need to define this function in your model

$userObj=new \App\User();
function whereName($name){
return $this->where('name',$name)->first();

Illuminate\Database\Query\Builder, array, $aggregate, An aggregate function and column to be run. array, $columns, The columns static bool. hasMacro(string $name). Checks if macro is registered. Throw an exception if the query doesn't have an orderBy clause. Collection. addArrayOfWheres (array $column, string $boolean, string $method = 'where') Add an array of where clauses to the query.

Eloquent: Getting Started - Laravel, By convention, the "snake case", plural name of the class will be used as the table If you do not wish to have these columns automatically managed by Eloquent, set the The fresh method will re-retrieve the model from the database . If your global scope is adding columns to the select clause of the query, you should� Browse other questions tagged php laravel eloquent relationship where-clause or ask your own question. The Overflow Blog Podcast 265: the tiny open-source pillar holding up the entire internet

@voodoo417 Read the comment again - it's not about what you do to make it secure, but what Laravel does for you. Using havingRaw simply means, that passed variable won't be bound in PDO statement, period.

You have configured the auth.php and used members table for authentication but there is no user_email field in the members table so, Laravel says. SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '', ))

  • This is called where magic method. I have found documentation Dynamic Where Clauses
  • Thanks, This really solves my desire to know where the function is defined and how it returns its value.
  • Not what OP is asking.
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review