This i called table data gateway pattern where a tables responsibility is handled by a Repository(data gateway)
First download toad from MySql freeware for browsing DB.
If you use phpmyadmin Ui then XDebug will create different problem including auto debug point …So be sure to use Toad ;;koc
1 2 3 4 5 6 7 8 9 |
--Create a table in MySql Database create table test ( id INTEGER AUTO_INCREMENT PRIMARY KEY, name TEXT ) insert into test values(1,'akash'); select * from test; |
–Make a model in app\Http\Models
php artisan make:model Http/Models/Test
and specify your table
1 2 3 4 5 |
class Test extends Model { protected $table = 'test'; public $timestamps = false; } |
Create a TestRepository in App\Http\Repositories folder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php namespace App\Http\Repositories; use App\Http\Models\Test as test; class TestRepository{ //Read public function get(){ $all=test::all(); return $all; } public function getById($id){ $val=test::find($id); return $val; } //..More read may necessary for different environment //Create public function set($id,$name){ $t = new test; $t->id=$id; $t->name=$name; $t->save(); //return true or false } //Update public function update($id,$name){ $val=test::find($id); $val->name=$name; $val->save(); //return true or false } //...More update by column name //Delete public function delete($id){ return test::destroy($id); //Return int .the number of row.If not found delete no thing } } |
and finally inject it to Controller as much you as want. Separate all model with repository for
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class HelloController extends Controller { protected $testRepository; public function __construct(TestRepository $testRepository) //Depedecy injection here .... { $this->testRepository = $testRepository; } public function index() { $allData=$this->testRepository->get(); $singledata=$this->testRepository->getById(5); $this->testRepository->set(6,"holo"); $this->testRepository->update(3,'New Updated Name'); $noOfDeletedRows= $this->testRepository->delete(2); //dd($allData); return view('welcome'); } } |
**Aditional Info
php artisan make:controller HelloController
Route::get(‘/’,’HelloController@welcome’);
//Create a dummy repository for copy and paste