Reputation: 191
What is the better place to write out database queries in Laravel?
In Controllers or in Models?
Please let me know which way is correct:
Using in controllers like this?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB; // <--------
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function getUser()
{
return DB::table('users')->where('name', 'John')->value('email');
}
}
Using in models like this?
<?php
namespace App\Models;
use DB; // <--------
use Illuminate\Database\Eloquent\Model;
class UsersModel extends Model
{
protected $table = 'users';
public function getUser()
{
return DB::table('users')->where('name', 'John')->value('email');
}
}
Or none of the above?
Upvotes: 1
Views: 1972
Reputation: 260
The topic of where you should place your queries is a common one. It ultimately comes down to your personal preference and your particular situation.
If you need to reuse the query elsewhere I would recommend placing the query within your model. However, I must warn you that you may encounter problems when using this option because changing the query can have unexpected results, if the query is used in multiple places within your application.
If you do not need to reuse the query, place it within the controller. This way you never have to worry about the query changing and breaking your controller method.
To answer your question, there is no definite place where you should place queries. All I can suggest is don't overcomplicate your solution, and don't try to shoehorn all your queries into one pattern.
There are other options to the two examples you provided though. For more information on these check out these videos:
Upvotes: 0
Reputation: 5169
Your usage here is actually better solved with scopes.
use Illuminate\Eloquent\Database\Builder;
use Illuminate\Eloquent\Database\Model;
class User extends Model
{
// Did you know that if your model name is the singular version of your table name, you don't need to include this?
protected $table = 'users';
public function scopeForName(Builder $query, $name)
{
return $query->where('name', $name);
}
}
And now usage is this:
$user = User::forName('John')->email;
Upvotes: 1
Reputation: 163978
Academically, it's better to keep all data based logic inside models only. But on practice it's more convinient to keep simple queries inside a controller and use scopes for repeated stuff. You get more readable and easier to maintain code in this case. Also, all Laravel books suggest the same.
Anyway it's more opinion based.
Upvotes: 2