Laravel Crud Helper
A simple laravel crud helper to let programmers stop repeating themselves.
<?php
class CrudController extends BaseController {
public function index()
{
try
{
$model = Input::get('modelname');
$data['items'] = $model::all();
return Response::Json($data, 200);
}
catch(Exception $e) {
$message = 'Caught exception: '. $e->getMessage(). "n";
$data = ['status'=>False,'message'=>$message ];
return Response::Json($data, 303);
}
}
public function store()
{
try
{
$user_id = Auth::user()->id;
$data = Input::all('data');
$tablename = Input::get('tablename');
$model = Input::get('modelname');
$validator = Validator::make($data = $data, $model::$rules);
if ($validator->fails())
{
$data['message'] = 'Please fill required fields';
return Response::Json($data, 301);
}
$arguments = array_except($data, array('modelname','tablename'));
$status = $model::create($arguments);
$inserted_id = $status->id;
$data['insertedData'] = DB::table($tablename)->where('id', $inserted_id)->first();
$data['message'] = $model.' successfully saved';
return Response::Json($data, 200);
}
catch(Exception $e) {
$message = 'Caught exception: '. $e->getMessage(). "n";
$data = ['status' =>False,'error_message'=>$message ,
'message' =>'Unable to save '.$model. ', Please try again.'
];
return Response::Json($data, 303);
}
}
public function show()
{
try
{
$model = Input::get('modelname');
$id = Input::get('id');
$data['item'] = $model::findOrFail($id);
return Response::Json($data, 200);
}
catch(Exception $e) {
$message = 'Caught exception: '. $e->getMessage(). "n";
$data = ['status'=>False,'message'=>$message ];
return Response::Json($data, 303);
}
}
public function update()
{
try
{
$model = Input::get('modelname');
$id = Input::get('id');
$data = Input::get('data');
$obj = json_decode($data, true);
foreach ($obj as $key => $value) {
$column_name = $key;
$column_value = $value;
$status = $model::findOrFail($id);
$status->$column_name = $column_value;
$status->updated_at = time();
$status->save();
}
if($status->save() ==1 ){
$data = ['status'=>True, 'message'=>$model.' successfuly updated'];
}else{
$data = ['status'=>False,'message'=>$model.' doesnt exist' ];
}
return Response::Json($data, 200);
}
catch(Exception $e) {
$message = 'Caught exception: '. $e->getMessage(). "n";
$data = ['status'=>False,'message'=>$message ];
return Response::Json($data, 303);
}
}
public function destroy()
{
try
{
$id = Input::get('id');
$model = Input::get('modelname');
if($model::findOrFail($id)->delete() ==1 ){
$data = ['status'=>True, 'message'=>$model.' successfully deleted'];
}else{
$data = ['status'=>False,'message'=>$model.' doesnt exist' ];
}
return Response::Json($data, 200);
}
catch(Exception $e) {
$message = 'Caught exception: '. $e->getMessage(). "n";
$data = ['status'=>False,'message'=>$message ];
return Response::Json($data, 303);
}
}
}
Language: PHP | User: wattay.shadrack@gmail.com | Created: May 3, 2015 | Tags: Laravel REST CRUD