Mounting a query with laravel

6

I'm studying the laravel structure from this ready-made example = > bestmomo .

In the project there is the userRepository repository with the following structure:

<?php

namespace App\Repositories;

use App\Models\User;

class UserRepository
{
    /**
     * Get users collection paginate.
     *
     * @param  int  $nbrPages
     * @param  array  $parameters
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAll($nbrPages, $parameters)
    {
        return User::with ('ingoing')
            ->orderBy ($parameters['order'], $parameters['direction'])
            ->when (($parameters['role'] !== 'all'), function ($query) use ($parameters) {
                $query->whereRole ($parameters['role']);
            })->when ($parameters['valid'], function ($query) {
                $query->whereValid (true);
            })->when ($parameters['confirmed'], function ($query) {
                $query->whereConfirmed (true);
            })->when ($parameters['new'], function ($query) {
                $query->has ('ingoing');
            })->paginate ($nbrPages);
    }
}

This structure makes use of the config file parameters :

<?php

return [

    'users' => [
        'order' => 'created_at',
        'direction' => 'desc',
        'role' => 'all',
        'valid' => false,
        'confirmed' => false,
        'new' => false,
    ],
    'posts' => [
        'order' => 'created_at',
        'direction' => 'desc',
        'new' => false,
        'active' => false,
    ],
    'contacts' => [
        'new' => false,
    ],
    'comments' => [
        'new' => false,
        'valid' => false,
    ],

];

The structure of the database is as follows:

Schema::create('users', function(Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->string('name')->unique();
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->enum('role', array('user', 'redac', 'admin'));
    $table->boolean('valid')->default(false);
});

I'm trying to understand these methods: whereRole , whereValid and whereConfirmed , I searched the entire project and did not find the structure of these methods, how does Laravel build these methods?     

asked by anonymous 24.11.2017 / 19:48

1 answer

3

This is one of the cool (and confusing things about Laravel).

These methods do not exist, they are short versions of the where method, what comes after this keyword is the name of the column that is part of where .

That is,

$query->whereRole('algumValor')

is exactly the same as

$query->where('role', 'algumValor')
  

How does Laravel fit these methods?

This has already been answered in: Is there any magic method for calling an attribute as a method in php?

    
24.11.2017 / 20:02