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?
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: