Laravel- getting i think POST message after set_date submit - php

Hello i have a form which sets the date of voting start and stop, today I started to get this information on my screen. Could anyone tell me what does it mean ?
This functionality uses 2 php files.
MakeVoteController in which i take the date from form and then do Carbon::create and put them into database and there's function in my VotingStatus model. It is checking if the current date is in between begin and end date then it returns voting_status(started or stopped)
VOTINGMGMT CONTROLLER
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
class VotingMgmtController extends Controller
{
public function start()
{
self::setStart();
return view('panel.startvoting');
}
public function stop()
{
self::setStop();
return view('panel.stopvoting');
} //
public function setDateView()
{
return view('panel.startvoting');
}
public function setDate(Request $request)
{
$rok_start = Input::get('rok');
$miesiac_start = Input::get('miesiac');
$dzien_start = Input::get('dzien');
$godzina_start = Input::get('godzina');
$minuta_start = Input::get('minuta');
$rok_stop = Input::get('rok_end');
$miesiac_stop = Input::get('miesiac_end');
$dzien_stop = Input::get('dzien_end');
$godzina_stop = Input::get('godzina_end');
$minuta_stop = Input::get('minuta_end');
$begin_date = Carbon::create($rok_start,$miesiac_start,$dzien_start,$godzina_start,$minuta_start,59,'Europe/Warsaw');
$stop_date = Carbon::create($rok_stop,$miesiac_stop,$dzien_stop,$godzina_stop,$minuta_stop,59,'Europe/Warsaw');
$now = Carbon::now('Europe/Warsaw');
//Set begin and end date in database
DB::table('voting_status')
->where('id',1)
->update(['voting_start_date' => $begin_date]);
DB::table('voting_status')
->where('id',1)
->update(['voting_end_date' => $stop_date]);
return redirect()->route('set_date')->with('success','Ustawiono datę rozpoczęcia i zakończenia głosowania');
}
public function setEndDate()
{
}
private function setStart()
{
try
{
DB::table('voting_status')
->where('id',1)
->update(['status' => 'started']);
}
catch(\Illuminate\Database\QueryException $ex)
{
return view('info.dash_service_unavailable');
}
}
private function setStop()
{
try
{
DB::table('voting_status')
->where('id',1)
->update(['status' => 'stopped']);
}
catch(\Illuminate\Database\QueryException $ex)
{
return view('info.dash_service_unavailable');
}
return true;
}
private function checkDate()
{
}
}
VOTINGSTATUS MODEL
<?php
namespace App;
use DB;
use PDO;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class VotingStatus extends Model
{
protected $table = "voting_status";
//check table VotingStatus whether started or not
function checkStatus()
{
/*query database about status of voting and
print output */
DB::setFetchMode(PDO::FETCH_ASSOC);
$begin_date = DB::select('select voting_start_date from voting_status where id=1 ');
$end_date = DB::select('select voting_end_date from voting_status where id=1');
$now = Carbon::now('Europe/Warsaw');
$begin_var;
$end_var;
foreach($begin_date as $key => $value)
{
$begin_var= (string)$value['voting_start_date'];
echo $begin_var;
}
foreach($end_date as $key => $value)
{
$end_var= (string)$value['voting_end_date'];
echo $end_var;
}
$carbon_start = Carbon::parse($begin_var,'Europe/Warsaw');
$carbon_stop = Carbon::parse($end_var,'Europe/Warsaw');
if(($now->gt($carbon_start)) && ($now->lt($carbon_stop)))
{
try
{
DB::table('voting_status')
->where('id',1)
->update(['status' => 'started']);
}
catch(\Illuminate\Database\QueryException $ex)
{
dd("Upss start");
}
}
else
{
try
{
DB::table('voting_status')
->where('id',1)
->update(['status' => 'stopped']);
}
catch(\Illuminate\Database\QueryException $ex)
{
dd("Upss stop");
}
}
DB::setFetchMode(PDO::FETCH_CLASS);
$db_stat = DB::table('voting_status')->where('id',1)->first();
$status = $db_stat->status;
return $status;
}
}
FORM

Error has been fixed. After uploading newer version of application on the server there still was old version of web.php. In mentioned web.php my form submit was handled by function
set_date(Request $request)
{
return $request;
}
Now everything works

Related

Problem when trying to validate email that already exists in database

I am building custom mvc framework in php in order to learn and when I am trying to submit my form with an mail that already exists in the database, my validation should prevent me to do so, instead I get this error:
Fatal error: Uncaught Error: Call to a member function findUserByEmail() on null in C:\xampp\htdocs\gacho\App\Controllers\UsersController.php:
UsersController.php
<?php
namespace App\Controllers;
use App\Models\User;
use Core\Controller;
class UsersController extends Controller
{
public function __construct($controller, $action)
{
parent::__construct($controller, $action);
$this->userModel = $this->load_model('User');
}
public function registerAction()
{
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
'email' => trim($_POST['email']),
];
}
if (empty($data['email'])) {
$data['email_err'] = "Please enter your email!!!";
} else {
if ($this->userModel->findUserByEmail($data['email'])) {
$data['email_err'] = "Email is already taken!";
}
}
}
User.php
<?php
namespace App\Models;
use Core\Database;
class User
{
private $db;
public function __construct()
{
$this->db = new Database();
}
public function findUserByEmail($email)
{
$this->db->query('SELECT * FROM users WHERE email = :email');
$this->db->bind(':email', $email);
$row = $this->db->single();
if ($this->db->rowCount() > 0) {
return true;
} else {
return false;
}
}
}
Controller.php:
<?php
namespace Core;
class Controller
{
protected $_controller;
protected $_action;
public $view;
public function __construct($controller, $action)
{
$this->_controller = $controller;
$this->_action = $action;
$this->view = new View();
}
protected function load_model($model)
{
$modelPath = 'App\Models\\' . $model;
if (class_exists($modelPath)) {
$this->{$model.'Model'} = new $modelPath();
}
}
}
I think the mistake is about $this->userModel , but I'm stuck and any help is appreciated.
The problem is that in __construct of UsersController you have:
$this->userModel = $this->load_model('User');
So you assign to userModel property the return value of load_model method.
load_model method doesn't return anything so $this->userModel is always set to NULL, doesn't matter if load_model succeeded or not.
You should just return new $modelPath(); in load_model if you want to assign it to a property by return value.
Also add throw new Exception($modelPath. 'not found'); at the end of load_model method to be sure it did load the model, and not just failed silently to find it.
Note that $this->userModel is not the same as $this->UserModel (case sensitive) and $modelPath = 'App\Models\\' . $model; - why \ after App, and two \ after Models?
I think you need to access your model in $this->UserModel, since User was passed into the load_model method.

Code called in schedular deletes the records in table but doesnt add

My controller kernel is like this
protected function schedule(Schedule $schedule)
{
$schedule->call('\App\Http\Controllers\HomeController#automatic')->everyMinute();
}
When i call the controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Storage;
use App\news;
use Auth;
use DOMDocument;
use Exception;
class HomeController extends Controller
{
public function automatic()
{
function delete(){
DB::table('news')->delete();
echo "table deletted";
}
delete();
}
}
It deletes the records in the table. But when i call controller having this code
class HomeController extends Controller
{
public function automatic()
{
function follow_links_reportersnepal($url,$cat)
{
ini_set('max_execution_time', 9000);
global $already_crawled;
global $crawling;
$i=0;
$doc = new DOMDocument();
#$doc->loadHTML(#file_get_contents($url));
$linklist = $doc->getElementsByTagName("a");
$already_crawled[]="sailaab";
foreach ($linklist as $link)
{
try {
$l = $link->getAttribute("href");
if(strlen($l)==45)
{
if (!in_array($l, $already_crawled))
{
$i++;
if ($i>2) {
break;
}
$already_crawled[] = $l;
$content = file_get_contents($l);
$first_step = explode( '<h3 class="display-4">' , $content);
$second_step = explode('</h3>' , $first_step[1]);//title
$third_step=explode('<div class="entry-content">',$second_step[1]);
$fourth_step=explode('<p>',$third_step[1]);
$fifth_step=explode('<div class="at-below-post', $fourth_step[1]);
$sixth_step=explode('<figure class="figure">', $content);
if(isset($sixth_step[1])){
$seventh_step=explode('src="', $sixth_step[1]);
$eighth_step=explode('"', $seventh_step[1]);
$url = $eighth_step[0];
$img=rand();
$img=(string)$img;
file_put_contents($img, file_get_contents($url));
$user = Auth::user();
news::create([
'news_title'=>strip_tags($second_step[0]),
'category_id'=>$cat,
'source_id'=>'reportersnepal',
'reference_url'=>"www.reportersnepal.com",
'reference_detail'=>$l,
'news_summary'=>"null",
'news_detail'=>strip_tags($fifth_step[0]),
'news_image'=>$img,
'news_video'=>"null",
'news_status'=>"1",
'created_by'=>$user->id,
'last_updated_by'=>$user->id,
]);
}
else{
$user = Auth::user();
news::create([
'news_title'=>strip_tags($second_step[0]),
'category_id'=>$cat,
'source_id'=>'reportersnepal',
'reference_url'=>"www.reportersnepal.com",
'reference_detail'=>$l,
'news_summary'=>"null",
'news_detail'=>strip_tags($fifth_step[0]),
'news_image'=>"default.png",
'news_video'=>"null",
'news_status'=>"1",
'created_by'=>$user->id,
'last_updated_by'=>$user->id,
]);
}
}
}
} catch (Exception $e) {
continue;
}
}
}
follow_links_reportersnepal('http://reportersnepal.com/category/featured','1');
}
}
It doesnt write anything in my database table. When i echo the variables it dispays the data.
This code works fine when i call them manually.
And my cron tab is
php-cli -q /home/allnewsnepal/public_html/artisan schedule:run
Laravel scheduler are command line based and you cannot use session and Auth components there
Your code below dont make any sense here
$user = Auth::user();
You need to store user information on some other in memory database like redis and then use it

Laravel one to many relationship insert data

I have two tables notification and alerFrequency. they have a one to many relationships respectively. the notification_id is a foreign key in the alerFrequency table. Both tables have models. now what I am trying to do is, to automatically insert data into the alertFrequency table if website is add in the notification table. this is the notification table
<?php
namespace App;
use App\Status;
use App\Notification;
use App\AlertFrequency;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
public function alertFrequencies(){
return $this->hasMany('App\AlertFrequency');
}
public function alert(){
$alert_timestamp = AlertFrequency::with('notification')->orderBy('created_at','desc')->select('created_at')->first();
$alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
if($alert_timestamp==null){
return false;
}
return $alert_timestamp; }
and in the guzzle controller, I am using 3 functions: the add function to add a new alertFrequency into the table (which is not working at all) and the I called it in the sendnotification function, so that if it is time to send notification, it will add a new created_at in the alerFrequency table. Here is the guzzle controller
<?php
namespace App\Http\Controllers;
use \GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
use Carbon;
use App\AlertFrequency;
class GuzzleController extends Controller
{
private $default_check_frequency;
protected $client;
protected $reporter;
public function __construct()
{
$this->client = new Client();
$this->reporter = new Reporter;
$this->default_check_frequency = Setting::defaultCheckFrequency();
}
private function addStatusToNotification(Notification $notification, Status $status, $resCode)
{
$notification->statuses()->attach($status, [
'values' => strval($resCode)
]);
}
/*function to add new time stamp into the alertFrequency table*/
private function add(Notification $notification, AlertFrequency $alert){
$notification->alertFrequency()->save();
}
private function report(Notification $notification, $resCode)
{
if(empty($resCode)){
$resCode = "no response found";
}
$status = Notification::health($resCode);
$this->reporter->slack($notification->website_url . ':' . ' is '. $status . ' this is the status code!' . ' #- ' .$resCode, $notification->slack_channel);
$this->reporter->mail($notification->email,$notification->website_url.' is '. $status . ' this is the status Code: '. $resCode);
}
private function sendNotification(Notification $notification, $status_health, $alert_frequency, $resCode,$alert)
{
echo "elpse time alert";
var_dump(\Carbon\Carbon::parse($alert)->diffInMinutes());
// If this is the first time we check, OR if the status changed from up to down and vice versa, notify!!!
if (empty($status_health['timestamp']) || Notification::health($resCode) <> Notification::health($status_health['value'])){
$this->report($notification,$resCode);
return;
}
// If the website is (still) down and the alert frequency is exceeded, notify!!!
if(Notification::health($resCode) === 'down' && \Carbon\Carbon::parse($alert)->diffInMinutes() >= $alert_frequency){
$this->report($notification,$resCode);
$this->add($notification,$alert);
}
}
public function status()
{
$notifications = Notification::where('active', 1)->get();
//$alert = AlertFrequency::
$status = Status::where('name', 'health')->first();
foreach ($notifications as $notification) {
$frequency = $this->updateStatus($notification, $status);
if (!empty($frequency)) {
$notification->alertFrequencies()->create([
'notification_id' => $frequency
]);
}
}
}
private function updateStatus(Notification $notification, Status $status)
{
$status_health = $notification->status('health');
$check = empty($status_health['timestamp']);
$elapsed_time = $check ? 10000 : \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();
$check_frequency = $this->getCheckFrequency($notification);
/* create an attachemtn in to the alerFrequenct table*/
$alert = $notification->alert();
var_dump($alert);
if ($check || $elapsed_time >= $check_frequency) {
$resCode = $this->getStatusCode($notification->website_url);
$this->addStatusToNotification($notification, $status, $resCode);
$this->sendNotification(
$notification,
$status_health,
$this->getAlertFrequency($notification),
$resCode,
$alert
);
}
}
private function getCheckFrequency(Notification $notification)
{
return isset($notification->check_frequency)
? intval($notification->check_frequency)
: $this->default_check_frequency;
}
private function getAlertFrequency(Notification $notification)
{
return isset($notification->alert_frequency)
? intval($notification->alert_frequency)
: $this->default_check_frequency;
}
private function getStatusCode($url)
{
try {
$response = $this->client->get($url, [
'http_errors' => false
]);
return $response->getStatusCode();
} catch (\GuzzleHttp\Exception\ConnectException $e) {
}
}
}

Laravel 5.2 understanding "fat model, skinny controller"

I'm trying to understand how to use "fat model, skinny controller" in Laravel 5.2. Basically, I mostly understand the why, and the what, but not the how. I've been Googling for a while, and I have found several pages describing why (and some pages describing why not) and what, but no pages that makes it easy to understand how you create a fat model with skinny controllers.
I have created a extremely basic Todo-list, no login or validation, just the most basic todo-note functionality. This application basically uses "skinny model, fat controllers" and I want to rewrite the app so that it uses "fat model, skinny controllers" instead.
I have three tables in the MySQL-database:
users
id int(10)
uname varchar(255)
email varchar(255)
password varchar(60)
projects
id int(10)
pname varchar(255)
notes
id int(10)
user_id int(10)
project_id int(10)
content text
time_created timestamp
time_deadline timestamp
completed tinyint(1)
removed tinyint(1)
When I created the migrations for the tables, I used $table->foreign('user_id')->references('id')->on('users'); and $table->foreign('project_id')->references('id')->on('projects'); for the notes table migration. For some reason it did not work, so in the database notes.user_id and notes.project_id are not foreign keys to users.id and projects.id, which was the idea from the beginning. I'm guessing that it doesn't really matter for my questions below, but if it does, someone please tell me so I can try to fix that.
I have the following models (doc blocks removed)
app\User.php:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function notes()
{
return $this->hasMany(Note::class);
}
}
app\Project.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function notes()
{
return $this->hasMany(Note::class);
}
}
app\Note.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function project()
{
return $this->belongsTo(Project::class);
}
}
I have the following controllers (doc blocks removed)
app\Http\Controllers\UserController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Response;
class UserController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$users = User::orderBy('uname', 'asc')->get()->toArray();
$response = [];
foreach ($users as $user) {
$this_row = array(
'id' => $user['id'],
'name' => $user['uname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
app\Http\Controllers\ProjectController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Project;
use Response;
class ProjectController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$projects = Project::orderBy('pname', 'asc')->get()->toArray();
$response = [];
foreach ($projects as $project) {
$this_row = array(
'id' => $project['id'],
'name' => $project['pname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
app\Http\Controllers\NoteController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Note;
use App\User;
use App\Project;
use Input;
use Response;
use Redirect;
class NoteController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$notes = Note::where('removed', 0)
->orderBy('time_created', 'asc')->get()->toArray();
$response = [];
foreach ($notes as $note) {
$user = User::find($note['user_id']); // Username for note
$project = Project::find($note['project_id']); // Project name
$this_row = array(
'id' => $note['id'],
'user' => $user['uname'],
'project' => $project['pname'],
'content' => $note['content'],
'completed' => $note['completed'],
'created' => $note['time_created'],
'deadline' => $note['time_deadline']
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
public function destroy(Request $request)
{
try {
$statusCode = 200;
$note = Note::find($request->id);
$note->removed = 1;
$note->save();
} catch (Exception $e) {
$statusCode = 400;
} finally {
return $statusCode;
}
}
public function edit($request)
{
try {
$statusCode = 200;
$note = Note::find($request);
$response = array(
'id' => $note['id'],
'content' => $note['content'],
'completed' => $note['completed'],
'deadline' => $note['time_deadline']
);
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
public function update(Request $request)
{
try {
$statusCode = 200;
$note = Note::find($request->id);
$note->content = $request->content;
$note->time_deadline = $request->deadline;
if ($request->completed == "true") {
$note->completed = 1;
} else {
$note->completed = 0;
}
$note->save();
} catch (Exception $e) {
$statusCode = 400;
} finally {
return $statusCode;
}
}
public function store(Request $request)
{
try {
$statusCode = 200;
$note = new Note;
$note->user_id = $request->user;
$note->project_id = $request->project;
$note->content = $request->content;
$note->time_deadline = $request->deadline;
$note->save();
} catch (Exception $e) {
$statusCode = 400;
} finally {
return $statusCode;
}
}
}
Finally, this is my app/Http/routes.php (comments removed)
<?php
Route::get('/', function () {
return view('index');
});
Route::get('/notes', 'NoteController#index');
Route::get('/notes/{id}', 'NoteController#edit');
Route::delete('/notes', 'NoteController#destroy');
Route::put('/notes', 'NoteController#store');
Route::post('/notes', 'NoteController#update');
Route::get('/projects', 'ProjectController#index');
Route::get('/users', 'UserController#index');
Route::group(['middleware' => ['web']], function () {
//
});
The complete code can be found at my GitHub here.
I'm using Angular to receive the JSON sent by the controllers. This works fine for my current page but as you can see, my controllers have a lot of logic, which I would like to move to the model. I don't understand how I do this, so here's my questions:
Which additional files should I create?
Where should they be located?
What do I need in those files except the logic that currently is in the controllers?
How should I rewrite the controllers to handle the data from the models?
Your skinny controller could be the following, which will do the same what you did:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Project;
class ProjectController extends Controller
{
public function index()
{
$projects = Project::orderBy('pname', 'asc')->get(['id', 'name']);
return response()->make($projects);
}
}
But as Fabio mentioned, if you want to go further, checkout repositories. Here is a good article: https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/
In most cases I'm wrapping repositories into services to create the business logic. Controllers just handle routing, and models only contains relations or mutators and accessors. But it could differ by development methods.
Also, don't make db queries in foreach loops, take the advantage of Eloquent with, forexample:
$notes = Note::where('removed', 0)
->with(['user', 'project'])
->orderBy('time_created', 'asc')->get();
And you can access, like this:
foreach($notes as $note)
{
echo $note->user->uname;
}

Laravel Form Request : bad method be called

When I use a Form Request with a Post method the response is the "index()" method response. But it's have to be the "store(myRequest $request)" method.
If I remove myRequest $request method from "store()" it's works. I'm lost.Please help me.
My controller :
<?php namespace App\Http\Controllers\Ressource;
use App\Http\Requests\CreateCollectionRequest;
use App\Repositories\CollectionRepository;
class CollectionController extends RessourceController {
private $collectionRepository;
public function __construct(CollectionRepository $collectionRepository)
{
parent::__construct();
$this->collectionRepository = $collectionRepository;
}
public function index()
{
return $this->run( function()
{
return $this->collectionRepository->all()->get();
});
}
public function store(CreateCollectionRequest $request)
{
return $this->run( function() use ($request) {
return $this->collectionRepository->create($request->all());
});
}
}
RessourceController :
<?php namespace App\Http\Controllers\Ressource;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\Controller;
abstract class RessourceController extends Controller
{
protected $result = null;
public function __construct()
{
$this->result = new \stdClass();
$this->result->error = 0;
$this->result->message = '';
$this->result->service = $this->getService();
$this->result->data = null;
}
abstract public function getService();
protected function render()
{
return Response::json($this->result);
}
public function missingMethod($parameters = [])
{
$this->result->err = 404;
$this->result->message = 'Service ' . $this->getService() . ' : ' . $parameters . ' non disponible';
return $this->render();
}
protected function run($function)
{
try {
$this->result->data = call_user_func($function);
} catch (\Exception $e) {
$this->result->err = ($e->getCode() > 0) ? $e->getCode() : -1;
$this->result->message = $e->getMessage();
}
return $this->render();
}
}
Custom Form Request :
namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateCollectionRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'label' => 'required|alpha_num|min:3|max:32',
'description' => 'alpha_dash|max:65000',
'parent_collection_id' => 'exists:collections,id'
];
}
}
Extract from routes.php :
Route::group(array('namespace' => 'Ressource', 'prefix' => 'ressource'), function () {
Route::resource('collection', 'CollectionController', ['only' => ['index', 'show', 'store', 'update', 'destroy']]);
});
Postman request :
Postman reponse :
You should make your function become Clouse function.
My controller :
use App\Http\Requests\CreateCollectionRequest;
use App\Repositories\CollectionRepository;
use SuperClosure\Serializer;
use Illuminate\Support\Str;
use Closure;
class CollectionController extends RessourceController {
private $collectionRepository;
public function __construct(CollectionRepository $collectionRepository)
{
parent::__construct();
$this->collectionRepository = $collectionRepository;
}
public function index()
{
return $this->run( function()
{
return $this->collectionRepository->all()->get();
});
}
protected function buildCallable($callback) {
if (! $callback instanceof Closure) {
return $callback;
}
return (new Serializer)->serialize($callback);
}
public function store(CreateCollectionRequest $request)
{
$callback = function() use ($request) {
return $this->collectionRepository->create($request->all());
}
return $this->run($this->buildCallable($callback));
}
}
RessourceController :
<?php namespace App\Http\Controllers\Ressource;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\Controller;
use SuperClosure\Serializer;
use Illuminate\Support\Str;
use Closure;
abstract class RessourceController extends Controller
{
protected $result = null;
public function __construct()
{
$this->result = new \stdClass();
$this->result->error = 0;
$this->result->message = '';
$this->result->service = $this->getService();
$this->result->data = null;
}
abstract public function getService();
protected function render()
{
return Response::json($this->result);
}
public function missingMethod($parameters = [])
{
$this->result->err = 404;
$this->result->message = 'Service ' . $this->getService() . ' : ' . $parameters . ' non disponible';
return $this->render();
}
protected function getCallable($callback)
{
if (Str::contains($callback, 'SerializableClosure')) {
return unserialize($callback)->getClosure();
}
return $callback;
}
protected function run($function)
{
try {
$this->result->data = call_user_func($this->getCallable($function));
} catch (\Exception $e) {
$this->result->err = ($e->getCode() > 0) ? $e->getCode() : -1;
$this->result->message = $e->getMessage();
}
return $this->render();
}
}

Categories