Laravel API Route

645

Retrieve All data from a table

Create the Controller: php artisan make:Controller Country\CountryController;
Here is creating the controller in the Country Folder. Then create the route.
Create the route: Go to routes>api.php
Route::get(‘country’, ‘Country\CountryController@country’);

Model File : CountryModel
We have to create a Model who is communicate with the Database table ‘_z_country’;
So, Creating a Country Model in the Model folder.
php artisan make:Model Model\CountryModel;
Adding a line to communicate with ‘_z_country’ table:
class CountryModel extends Model {
protected $table = ‘_z_country’;
}

Before creating the ‘country’ method in the ‘ Country\CountryController ‘
We have to add the created CountryModel at the top of the Country\CountryController : use App\Model\CountryModel;
Now we will create the ‘country’ method at Country\CountryController .
public function country(){
return response()->json(CountryModel::get(), 200);
}

Retrieve Data by ID from a Table:

Route:
Route::get(‘country/{id}’, ‘Country\CountryController@countryById’);
countryById Method at Controller:
public function countryById($id){
return response()->json(CountryModel::find($id), 200);
}

Insert A Record :
Route::post(‘country’, ‘Country\CountryController@countrySave);


CountryModel file : We have to some modification at CountryModel File.
class CountryModel extends Model{
protected $table = ‘_z_country’;
protected $fillable = [ // all fields of the table
‘iso’,
‘countryname’,
‘dname’,

….
….
…..

];
}
We have to add another line in the model just before the protected $fillable
public $timestamps = false;

Country\CountryController File :
public function saveCountry(Request $request){
$country = CountryModel::create($request->all());
return $response->json($country, 201);
}

Updating Data:

Route::put(‘country/{country}’, ‘ Country\CountryController@countryUpdate’);

CountryController countryUpdate Method:
public function countryUpdate(Request $request, CountryModel $country){
$country->update($request->all());
return response()->json($country, 200);
}