Laravel Form Request : bad method be called - php

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();
}
}

Related

how can i get auth user or any session in the my custom class and provider?

i have to get the company which user chooses but i can't get user data in my class and provider boot function .
user can have more than one company so user have to choose a company for some operations. But as i said , i can't get the company which user chooses.
Like this :
public function boot()
{
$user = Auth::user();
dd( $user ); // return null;
$bid = new Bid();
$show = $bid->check();
Blade::directive('bid',function() use($show){
return "<?php if( $show ) { ?>";
});
Blade::directive('endbid',function(){
return '<?php } ?>';
});
}
My other class :
<?php
namespace App\Services\Buying\Package;
use App\Services\Buying\Package\PackageInterface;
use App\Models\Company\Company;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\User;
class PackageBuying extends PackageQuery implements PackageInterface
{
private $company_id;
public function __construct()
{
$user = Auth::user();
dd( $user ); // return null
$this->setCompanyId($this->company_id);
}
public function setSession( Request $request )
{
$request->session()->get('selected-company');
}
public function company()
{
return $this->company_id;
}
public function package()
{
if ( $this->check() ) {
return $this->getPackage($this->company())->first();
}
return [];
}
public function features()
{
return (object)json_decode( $this->package()->features );
}
public function importantFeatures()
{
return (object)json_decode( $this->package()->important_features );
}
public function active()
{
return (bool) $this->getPackage()->firstOrFail()->active;
}
}
Actually if i got user data in the provider boot function , i could send data to my class .
May you please help me ?
Thanks in advance.
Put the code inside your construct function to calMethod function like this
public function callAction( $method, $parameters ) {
$user = Auth::user();
dd( $user ); // return null
$this->setCompanyId($this->company_id);
return parent::callAction( $method, $parameters );
}

How can I get the variable in the model for the controller?

I have a $send variable in my model. I want to use it on the controller. But I get an error. How can I call it to the controller?
Model:
public function register_user($send)
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return true;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$this->users->register_user();
$this->load->view('signup', $this->send);
}
You can declare a private variable, say send in your model and make getter and setter in your model class in an encapsulated way to get the value in the controller, like below:
Snippet:
Model:
<?php
class Yourmodel extends CI_Model{
private $send;
function __construct() {
parent::__construct();
$this->send = [];
}
public function register_user($send){
if($this->emailVerify()) {
$this->send = array(
'tipo' => 'Error.'
);
return true;
}
return false;
}
public function setSendValue($value){
$this->send = $value;
}
public function getSendValue(){
return $this->send;
}
}
Controller:
<?php
class Controller extends CI_Controller{
private $send;
public function __construct(){
parent::__construct();
$this->send = [];
}
public function register(){
$this->load->model('users');
if($this->users->register_user()){
$this->send = $this->users->getSendValue();
}
$this->load->view('signup', $this->send);
}
}
Replace your code modal and controller as follows:
You need not to declare $send in modal definition, as you are not passing any value while calling the same modal function.
modal positive return can be array $send itself
Catch value of modal function
Modal :
public function register_user()
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$send = $this->users->register_user();
//print_r($send); // You will get data here
$this->load->view('signup', $this->send);
}
Model
public function register_user($send = "")
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$sendRes = $this->users->register_user(); //now you can use this $send response variable
$this->load->view('signup', $this->send);
}

codeigniter restful api illegal string offset in several fields

I keep on getting this error in my codeigniter micro app restful api. When I post an item only the first letter is get saved with status code 400 being displayed.
here is my model file:
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->set($this->setCity($city, null))->insert('cities');
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id;
}
return null;
}
public function update($id, $city)
{
$this->db->set($this->setCity($city))->where('id')->update('cities');
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
As you can see setCity function treat $city variable as array. So you need to pass array to setCity function.
class Cities_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function save($city)
{
$this->db->insert('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> null)));
if ($this->db->affected_rows() > 0) {
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array(
'id' => $city['id'],
'name' => $city['name']
);
}
}
another thing is, Codeignitor having method insert_id() to know last insert id.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class Cities extends REST_Controller{
public function __construct() {
parent::__construct();
$this->load->model('cities_model');
}
public function index_get(){
$cities=$this->cities_model->get();
if(!is_null($cities))
{
$this->response(array('response'=>$cities),200);
}
else
{
$this->response(array('error'=>'cities cannot be found...'),404);
}
}
public function find_get($id){
if(!$id)
{
$this->respose(null,400);
}
$cit=$this->cities_model->get($id);
if(!is_null($cit))
{
$this->response(array('response'=> $cit),200);
}
else{
$this->response(array('error'=> 'data could not be found...'),404);
}
}
public function index_post(){
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$id=$this->cities_model->save($this->post('city'));
if(!is_null($id))
{
$this->response(array('response'=> $id),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, data could not be saved...'),REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put(){
// for put you need to pass id as parameter
// Use validation library, instead of checking just for value.
$this->load->library('form_validation');
$this->form_validation->set_rules('id','ID','trim|required|integer');
$this->form_validation->set_rules('city','City','trim|required');
if($this->form_validation->run() == FALSE)
{
// send back list of validation errors.
$this->response($this->validation_errors(),REST_Controller::HTTP_BAD_REQUEST);
}
$update=$this->cities_model->update($this->post('id'),$this->post('city'));
if(!is_null($update))
{
$this->response(array('response' => 'content updated successfully'),REST_Controller::HTTP_OK);
}
else
{
$this->response(array('error'=> 'sorry, technical error occurred, please try again later...'), REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_delete($id){
if(!$id)
{
$this->response(null,400);
}
$del=$this->cities_model->delete($id);
if(!is_null($del))
{
$this->response(array('response'=> 'item successfully deleted'),200);
}
else{
$this->response(array('error'=> 'delete operations could not be done...'),400);
}
}
}
here is the model file:
<?php
class Cities_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get($id=null)
{
if(!is_null($id))
{
$query=$this->db->select('*')->from('cities')->where('id',$id)->get();
if($query->num_rows()===1)
{
return $query->row_array();
}
return null;
}
$sql=$this->db->select('*')->from('cities')->get();
if($sql->num_rows()>0)
{
return $sql->result_array();
}
return null;
}
public function save($city)
{
$this->db->insert('cities', array('name'=>$city));
if($this->db->affected_rows()>0)
{
return $this->db->insert_id();
}
return null;
}
public function update($id, $city)
{
$this->db->where('id',$id)->update('cities',$this->setCity(array('name'=>$cit‌​y,'id'=> $id)));
if ($this->db->affected_rows() === 1) {
return true;
}
return false;
}
private function setCity($city)
{
return array('id'=>$city['id'],
'name'=>$city['name']
);
}
public function delete($id)
{
$this->db->where('id',$id)->delete('cities');
if($this->db->affected_rows()===1)
{
return true;
}
return false;
}
}

Laravel- getting i think POST message after set_date submit

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

Slim3 right way to set errors and check is user logged in

I'm a new user of Slim framework, I've a simple Slim 3 application, with sign in and sign up validation. But I'm not really sure if this is the right/best way to set errors and check if user is logged in -In order to redirect it to his account if session user.id exists.
I used a middleware: AuthMiddleware which includes:
class AuthMiddleware
{
protected $container;
public function __construct($container)
{
$this->container = $container;
}
public function __invoke($request, $response, $next)
{
if (isset($_SESSION['user.id']) && !empty($_SESSION['user.id'])) {
return $response->withRedirect($this->container->router->pathFor('user.index'));
}
$twig = $this->container->view->getEnvironment();
if (isset($_SESSION['validation'])) {
$twig->addGlobal('errors', $_SESSION['validation']['errors']);
$twig->addGlobal('values', $_SESSION['validation']['values']);
unset($_SESSION['validation']);
}
if (isset($_SESSION['auth.signup.success'])) {
$twig->addGlobal('auth_signup_success', $_SESSION['auth.signup.success']);
unset($_SESSION['auth.signup.success']);
}
if (isset($_SESSION['auth.signin.failed'])) {
$twig->addGlobal('auth_signin_failed', $_SESSION['auth.signin.failed']);
unset($_SESSION['auth.signin.failed']);
}
$response = $next($request, $response);
return $response;
}
}
And I used Twig for my views.
Session validation assigned in the validator.php which includes:
class Validator
{
protected $errors = [];
protected $values = [];
public function validate($request, $rules)
{
foreach ($rules as $field => $rule) {
$this->values[$field] = $request->getParam($field);
try {
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e) {
$this->errors[$field] = $e->getMessages()[0];
}
}
if ($this->failed()) {
$_SESSION['validation'] = [
'errors' => $this->errors,
'values' => $this->values,
];
}
return $this;
}
public function failed()
{
return !empty($this->errors);
}
}
Using Respect\Validation. Also, is this the right use of Middlewares?
Thanks in advance.
try creating a separate file for the methods, and calling it from the middleware:
<?php
class AuthMiddleware extends Middleware {
public function __invoke($request, $response, $next) {
if (!$this->container->auth->check()) {
$this->container->flash->addMessage('danger', 'Please sign in to continue.');
return $response->withRedirect($this->container->router->pathFor('auth.signin'));
}
$response = $next($request, $response);
return $response;
}
}
while the Auth class would have those methods to check:
<?php
public function check () {
return isset($_SESSION['user']);
}
public function user() {
if (isset($_SESSION['user'])) {
return User::find($_SESSION['user'])->first();
} else {
return false;
}
}
Don't forget to include the Auth Class within your $app:
<?php
$container['auth'] = function ($container) {
return new \App\Auth\Auth();
};

Categories