Reputation: 25
I am a beginner to laravel, have installed laravel4 and it works cool. Even I have done database configuration. If I want to fetch or insert or to do some database operation where I need to write database queries ? I wrote a simple code in router.php like below and am getting all values from the database. But I need to know where exactly do we need write this code snippet ? My am is to write a rest API. Please can some one help me out ?
$users = DB::table('user')->get();
return $users;
Upvotes: 0
Views: 59
Reputation: 3236
It depends How you design your routing. if you route like this
Route::get('/', array('as' => 'home', function () {
}));
then you can do query in your routing page like
Route::get('/', array('as' => 'home', function () {
$users = DB::table('user')->get();
return $users;
}));
But if you call a controller in your routing like
Route::get('/', array('as' => 'home', 'uses' => 'HomeController@showHome'));
then you can do query in showHome
method insideHomeController
controller
like
class HomeController extends BaseController {
public function showHome(){
$users = DB::table('user')->get();
return $users;
}
}
Note : Controller directory is app/controllers
Update
If you would like to use Model
then you need to create model in App/models
folder like
class User extends Eloquent {
protected $table = 'user';
public $timestamps = true; //if true then you need to keep two field in your table named `created_at` and `updated_at`
}
then query will be like this
$users = User::all();
return $users;
Upvotes: 1