How can i pass the data between two controllers? - php

Here ids my first controller "DataFormController"
class DataFormController extends \App\Http\Controllers\Controller
{
public function getDataForm(Request $request) {
$model = $request->model;
$uuid = $request->uuid;
//some codes
return response()->json(['status' => 'success',
'settings' => $settings, 'form' => $form,
'relations' => $relations, 'values' => $values,
'dates' => $dates, 'actions' => $actions,
'translations' => $translations, 'count' => $count,
'max' => $limitationMax, 'limitReached' => $limitReached,
200);
}
Routes for "DataFormController"
Route::group(['prefix' => 'app', 'middleware' => 'auth:api'], function() {
Route::get('data-form', '\Platform\Controllers\App\DataFormController#getDataForm');
})
I want to pass data "values","dates","count" from DataFormController to another controller "PointController"
class PointController extends Controller {
public function newTransaction(Request $request){
//Some codes
return response()->json([
'status'=>'success',
'mgs'=>$data
],200);
}
}
Routes for "PointController"
Route::group(['prefix' => 'campaign', 'middleware' => 'auth:customer'], function() {
Route::post('newTransaction', '\Platform\Controllers\Campaign\PointController#newTransaction');
})
How can i solve this problem?
In PointController I want to get the value of "dates","count","values" which are in DataFormController

use App\Http\Controllers\PointController;
class DataFormController extends Controller
{
public function getDataForm(Request $request) {
$model = $request->model;
$uuid = $request->uuid;
//some codes
$response = ['status' => 'success',
'settings' => $settings, 'form' => $form,
'relations' => $relations, 'values' => $values,
'dates' => $dates, 'actions' => $actions,
'translations' => $translations, 'count' => $count,
'max' => $limitationMax, 'limitReached' => $limitReached];
$transactionReq = new Request($response);
/**
* if you declared the newTransaction as static you
* can call that function as below
*/
PointController::newTransactionStatic($transactionReq);
/**
* If the function is not static
*/
$pointController = new PointController();
$pointController->newTransactionNonStatic($transactionReq);
return response()->json($response,200);
}
You can declare the functions as static or non static as you desire, if you want to get the request in pointcontroller :
class PointController extends Controller {
/**
* NON STATIC FUNCTION
*
* #param Request $request
* #return void
*/
public function newTransactionNonStatic(Request $request){
//Some codes
}
/**
* STATIC FUNCTION
*
* #param array $request
* #return void
*/
public static function newTransactionStatic(Request $request){
//Some codes
}
}
If you want to get the "dates","count","values" from DataFormController :
$pointsData = \Arr::only($response,['dates','count','values']);
/**
* if you declared the newTransaction as static you
* can call that function as below
*/
PointController::newTransactionStatic($pointsData);
/**
* If the function is not static
*/
$pointController = new PointController();
$pointController->newTransactionNonStatic($pointsData);
Since we are passing the values as array change it accordingly in the point controller
class PointController extends Controller {
/**
* NON STATIC FUNCTION
*
* #param array $request
* #return void
*/
public function newTransactionNonStatic(array $request){
$dates = $request['dates'];
$count = $request['count'];
$values = $request['values'];
/**
* Or for easier way call the extract php function
* eg : extract($request);
* then easily use the array keys as variables
* -> $dates, $count, $values etc.
*/
}
/**
* STATIC FUNCTION
*
* #param Request $request
* #return void
*/
public static function newTransactionStatic(array $request){
$dates = $request['dates'];
$count = $request['count'];
$values = $request['values'];
/**
* Or for easier way call the extract php function
* eg : extract($request);
* then easily use the array keys as variables
* -> $dates, $count, $values etc.
*/
}
}

Related

RestFul API For Delete And Update Get 403 Forbidden Codeigniter 4

Remember this is codeigniter 4.
I need help in here. I am learning to implement about the RestFul API in codeigniter 4.
Below is my detail code.
Routes :
$routes->resource('ApiManageMaintenance', ['controller' =>'App\Controllers\ApiData\ApiManageMaintenance']); // get, put, create, delete
ApiManageMaintenance.php :
<?php
namespace App\Controllers\ApiData;
use App\Controllers\BaseController;
use CodeIgniter\RESTful\ResourceController;
class ApiManageMaintenance extends ResourceController
{
function __construct()
{
$model = new Dennis_setting_model();
}
// equal to get
public function index()
{
$Medoo = new \App\Models\Dennis_medoo_model();
$result = $Medoo->SelectAllMaintenance();
$response = [
'status' => 200,
'error' => null,
'messages' => 'Pull Data Successfull',
'data' => $result
];
return json_encode($response);
}
// equal to post
public function create() {
$version = $this->request->getVar('version');
$reason = $this->request->getVar('reason');
if ($version == "" || $reason == "") {
$response = [
'status' => 102,
'error' => 'Data Error',
'messages' => 'Data Not Valid',
'data' => null
];
return json_encode($response);
}
$array = array ('version' => $version,
'reason' => $reason
);
$Medoo = new \App\Models\Dennis_medoo_model();
$Medoo->InsertNewMaintenance($array);
$response = [
'status' => 200,
'error' => null,
'messages' => 'Create New Maintenance Successfull',
'data' => null
];
return json_encode($response);
}
// equal to get
public function show($id = null) {
$Medoo = new \App\Models\Dennis_medoo_model();
$result = $Medoo->SelectAllMaintenance();
$response = [
'status' => 200,
'error' => null,
'messages' => 'Pull Data Successfull',
'data' => $result
];
return json_encode($response);
}
// equal to put
public function update($id = null) {
$data = $this->request->getRawInput();
$data['id'] = $id;
$response = [
'status' => 200,
'error' => null,
'messages' => 'Update Data Successfull',
'data' => null
];
return json_encode($response);
}
// equal to delete
public function delete($id = null) {
$Medoo = new \App\Models\Dennis_medoo_model();
$Medoo->DeleteMaintenance($id);
$response = [
'status' => 200,
'error' => null,
'messages' => 'Delete Data Successfull',
'data' => null
];
return json_encode($response);
}
}
Config Filter.php
<?php namespace Config;
use CodeIgniter\Config\BaseConfig;
class Filters extends BaseConfig
{
// Makes reading things below nicer,
// and simpler to change out script that's used.
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'auth' => \App\Filters\Auth::class,
'authaccess' => \App\Filters\AuthAccess::class
];
// Always applied before every request
public $globals = [
'before' => [
//'honeypot'
'csrf' => ['except' => [
'api/ApiManageMaintenance/delete'
]
]
],
'after' => [
'toolbar',
//'honeypot'
],
];
// Works on all of a particular HTTP method
// (GET, POST, etc) as BEFORE filters only
// like: 'post' => ['CSRF', 'throttle'],
public $methods = [
];
// List filter aliases and any before/after uri patterns
// that they should run on, like:
// 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']],
public $filters = [];
}
Note : I am using thirdparty database library => Medoo, So just ignore it. I am not using the build in framework database query in codeigniter for some reason because Medoo is looking light and simple for me.
Then For Is Working :
Restful API : create => Working => Test With Postman Method : POST
Restful API : show / index => Working => Test With Postman Method : GET
https://somedomain.id/index.php/ApiManageMaintenance
Then For Not Working :
Restful API : update => Not Working => Test With Postman Method : PUT
Restful API : delete => Not Working => Test With Postman Method : DELETE
https://somedomain.id/index.php/ApiManageMaintenance/7
Restful API delete and update both give me an error when try in postman :
403 - Forbidden: Access is denied. You do not have permission to view
this directory or page using the credentials that you supplied.
I also add execption in config => filter.php
public $globals = [
'before' => [
//'honeypot'
'csrf' => ['except' => [
'api/ApiManageMaintenance/delete'
]
]
],
];
I dont really understand the config filter.php but it seem this line of code will make the api delete working.
'csrf' => ['except' => [
'api/ApiManageMaintenance/delete'
]
]
Now my question are :
Is there any specific setup or configuration I miss or I need to do
for Restfu API to make API Restfull working ?
Any help from this community is very appreciate.
The Answer :
Create File Filter in Folder Filters in Codeigniter 4
Put this code :
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Codeigniter\API\ResponseTrait;
use Config\Services;
use Exception;
class FilterBasicAuth implements FilterInterface
{
use ResponseTrait;
public function before(RequestInterface $request, $arguments = null)
{
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
The main code is :
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}
Then in config Filters.php
put and add aliases this code :
public $aliases = [
'cors' => \App\Filters\FilterBasicAuth::class,
];
Note :
I use filter name FilterBasicAuth. You can change to yours and
make sure in the aliases change the name too.
Thats All.
okay the best way implelemnet restfull apici4
api ctl
<?php
namespace Modules\Shared\Controllers;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*
* #package CodeIgniter
*/
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;
use Modules\Auth\Config\Services;
use Myth\Auth\AuthTrait;
use Psr\Log\LoggerInterface;
use Modules\Shared\Interfaces\UrlAggregationInterface;
use Modules\Shared\Libraries\UrlAggregation;
class ApiController extends ResourceController
{
use AuthTrait;
protected $format = "";
public object $userObject;
public UrlAggregationInterface $urlAggregation;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* #var array
*/
protected $helpers = [
'cookie',
'url',
'from',
'filesystem',
'text',
'shared'
];
/**
* Constructor.
*
* #param RequestInterface $request
* #param ResponseInterface $response
* #param LoggerInterface $logger
*/
/**
* #var string
* Holds the session instance
*/
protected $session;
public function __construct()
{
$this->userObject = (object)[];
}
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
$this->urlAggregation = new UrlAggregation($request);
$requestWithUser = Services::requestWithUser();
$this->userObject = $requestWithUser->getUser();
}
}
group ctl
<?php namespace Modules\Auth\Controllers;
use Modules\Auth\Config\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;
class Group extends ApiController
{
/**
* index function
* #method : GET
*/
public function index()
{
$groupEntity = new GroupEntity();
$this->urlAggregation->dataMap($groupEntity->getDataMap());
$groupService = Services::groupService();
$findAllData = $groupService->index($this->urlAggregation);
return $this->respond([
'data' => $findAllData['data'],
'pager' => $findAllData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* show function
* #method : GET with params ID
*/
public function show($id = null)
{
$groupService = Services::groupService();
$findOneData = $groupService->show($id);
return $this->respond([
'data' => $findOneData['data'],
'pager' => $findOneData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
public function create()
{
$rules = [
'name' => 'required|min_length[3]|max_length[255]|is_unique[auth_groups.name]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->create($groupEntity);
return $this->respond([
'data' => ''
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/**
* update function
* #method : PUT or PATCH
*/
public function update($id = null)
{
//get request from Vue Js
//get request from Vue Js
$json = $this->request->getJSON();
if (!isset($id)) {
$id = $json->id;
}
$rules = [
'name' => 'if_exist|required|min_length[3]|max_length[255]',
'description' => 'required|min_length[3]|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$groupEntity = new GroupEntity((array)$this->request->getVar());
$groupService = Services::groupService();
$groupService->update($id, $groupEntity);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/**
* edit function
* #method : DELETE with params ID
*/
public function delete($id = null)
{
$groupService = Services::groupService();
$groupService->delete($id);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}
entitiy
<?php namespace Modules\Auth\Entities;
use \CodeIgniter\Entity;
use CodeIgniter\I18n\Time;
class GroupEntity extends Entity
{
protected $id;
protected $name;
protected $description;
//check type of data
// protected $casts = ['
// is_flag' => 'boolean'];
protected $attributes = [
'id' => null,
'name' => null,
'description' => null,
];
protected $datamap = [
];
protected $dates = [];
protected $casts = [];
protected $permissions = [];
protected $roles = [];
}
service leayer
<?php
namespace Modules\Auth\Services;
use Modules\Auth\Entities\GroupEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Interfaces\UrlAggregationInterface;
use Modules\Shared\Libraries\MainService;
use Myth\Auth\Authorization\GroupModel;
class GroupService extends MainService
{
private GroupModel $model;
public function __construct()
{
$this->model = new GroupModel();
}
/**
* index function
* #method : GET
* #param UrlAggregationInterface $urlAggregation
* #return array
*/
public function index(UrlAggregationInterface $urlAggregation)
{
$pipeLine = $urlAggregation->decodeQueryParam()->getPipeLine();
return $this->model->aggregatePagination($pipeLine);
}
/**
* show function
* #method : GET with params ID
* #param $id
* #return array
*/
public function show($id)
{
if (is_null($id)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
$result = $this->model->where('id', $id)->paginate(1, 'default');
if (is_null($result)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$data = [
'data' => $result,
'pager' => $this->model->pager->getDetails()
];
return $data;
}
/**
* create function
* #method : POST
* #param GroupEntity $entity
* #throws \ReflectionException
*/
public function create(GroupEntity $entity)
{
if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
if (!$this->model->save($entity)) {
helper('shared');
$this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST,serializeMessages($this->model->errors()));
}
}
/**
* update function
* #method : PUT or PATCH
* #param $id
* #param GroupEntity $entity
* #throws \ReflectionException
*/
public function update($id , GroupEntity $entity)
{
if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
if (!$this->model->update($id, $entity)) {
helper('shared');
$this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST,serializeMessages($this->model->errors()));
}
}
/**
* edit function
* #method : DELETE with params ID
* #param $id
*/
public function delete($id )
{
$deleteById = $this->model->find($id);
if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$this->model->delete($id);
}
public function getInsertId()
{
return $this->model->getInsertID();
}
}
this is part 2
<?php namespace Modules\Auth\Config;
use CodeIgniter\HTTP\UserAgent;
use Config\App;
use Config\Services as AppServices;
use Config\Services as BaseService;
use Modules\Auth\Libraries\RequestWithUser;
use Modules\Auth\Services\AuthService;
use Modules\Auth\Services\GroupsPermissionService;
use Modules\Auth\Services\PermissionService;
use Modules\Auth\Services\RoleRouteService;
use Modules\Auth\Services\GroupService;
use Modules\Auth\Services\UsersPermissionService;
class Services extends BaseService
{
//--------------------------------------------------------------------
/**
* The Request class models an HTTP request.
*
* #param App|null $config
* #param boolean $getShared
*
* #return RequestWithUser
*/
public static function requestWithUser(App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('requestWithUser', $config);
}
$config = $config ?? config('App');;
return new RequestWithUser(
$config,
AppServices::uri(),
'php://input',
new UserAgent()
);
}
//--------------------------------------------------------------------
public static function roleRoute($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('roleRoute');
}
return new RoleRouteService();
}
//--------------------------------------------------------------------
public static function authService($getShared = false)
{
if (!$getShared) {
return new AuthService();
}
return static::getSharedInstance('authService');
}
//--------------------------------------------------------------------
public static function groupService($getShared = false)
{
if (!$getShared) {
return new GroupService();
}
return static::getSharedInstance('groupService');
}
//--------------------------------------------------------------------
public static function permissionService($getShared = false)
{
if (!$getShared) {
return new PermissionService();
}
return static::getSharedInstance('permissionService');
}
//--------------------------------------------------------------------
public static function groupsPermissionService($getShared = false)
{
if (!$getShared) {
return new GroupsPermissionService();
}
return static::getSharedInstance('groupsPermissionService');
}
//--------------------------------------------------------------------
public static function userPermissionService($getShared = false)
{
if (!$getShared) {
return new UsersPermissionService();
}
return static::getSharedInstance('usersPermissionService');
}
//--------------------------------------------------------------------
}
model
<?php namespace Myth\Auth\Authorization;
use CodeIgniter\Model;
use Modules\Auth\Entities\GroupEntity;
use Modules\Shared\Models\Aggregation;
class GroupModel extends Aggregation
{
protected $table = 'auth_groups';
protected $primaryKey = 'id';
protected $returnType = GroupEntity::class;
protected $allowedFields = [
'name', 'description'
];
protected $useTimestamps = false;
protected $validationRules = [
'name' => 'required|max_length[255]|is_unique[auth_groups.name,name,{name}]',
'description' => 'max_length[255]',
];
protected $validationMessages = [];
protected $skipValidation = false;
//--------------------------------------------------------------------
// Users
//--------------------------------------------------------------------
/**
* Adds a single user to a single group.
*
* #param int $userId
* #param int $groupId
*
* #return bool
*/
public function addUserToGroup(int $userId, int $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
$data = [
'user_id' => (int) $userId,
'group_id' => (int) $groupId
];
return (bool) $this->db->table('auth_groups_users')->insert($data);
}
/**
* Removes a single user from a single group.
*
* #param int $userId
* #param int|string $groupId
*
* #return bool
*/
public function removeUserFromGroup(int $userId, $groupId)
{
cache()->delete("{$groupId}_users");
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where([
'user_id' => $userId,
'group_id' => (int) $groupId
])->delete();
}
/**
* Removes a single user from all groups.
*
* #param int $userId
*
* #return bool
*/
public function removeUserFromAllGroups(int $userId)
{
cache()->delete("{$userId}_groups");
cache()->delete("{$userId}_permissions");
return $this->db->table('auth_groups_users')
->where('user_id', (int)$userId)
->delete();
}
/**
* Returns an array of all groups that a user is a member of.
*
* #param int $userId
*
* #return array
*/
public function getGroupsForUser(int $userId)
{
if (null === $found = cache("{$userId}_groups"))
{
$found = $this->builder()
->select('auth_groups_users.*, auth_groups.name, auth_groups.description')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->where('user_id', $userId)
->get()->getResultArray();
cache()->save("{$userId}_groups", $found, 300);
}
return $found;
}
/**
* Returns an array of all users that are members of a group.
*
* #param int $groupId
*
* #return array
*/
public function getUsersForGroup(int $groupId)
{
if (null === $found = cache("{$groupId}_users"))
{
$found = $this->builder()
->select('auth_groups_users.*, users.*')
->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left')
->join('users', 'auth_groups_users.user_id = users.id', 'left')
->where('auth_groups.id', $groupId)
->get()->getResultArray();
cache()->save("{$groupId}_users", $found, 300);
}
return $found;
}
//--------------------------------------------------------------------
// Permissions
//--------------------------------------------------------------------
/**
* Gets all permissions for a group in a way that can be
* easily used to check against:
*
* [
* id => name,
* id => name
* ]
*
* #param int $groupId
*
* #return array
*/
public function getPermissionsForGroup(int $groupId): array
{
$permissionModel = model(PermissionModel::class);
$fromGroup = $permissionModel
->select('auth_permissions.*')
->join('auth_groups_permissions', 'auth_groups_permissions.permission_id = auth_permissions.id', 'inner')
->where('group_id', $groupId)
->findAll();
$found = [];
foreach ($fromGroup as $permission)
{
$found[$permission['id']] = $permission;
}
return $found;
}
/**
* Add a single permission to a single group, by IDs.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function addPermissionToGroup(int $permissionId, int $groupId)
{
$data = [
'permission_id' => (int)$permissionId,
'group_id' => (int)$groupId
];
return $this->db->table('auth_groups_permissions')->insert($data);
}
//--------------------------------------------------------------------
/**
* Removes a single permission from a single group.
*
* #param int $permissionId
* #param int $groupId
*
* #return mixed
*/
public function removePermissionFromGroup(int $permissionId, int $groupId)
{
return $this->db->table('auth_groups_permissions')
->where([
'permission_id' => $permissionId,
'group_id' => $groupId
])->delete();
}
//--------------------------------------------------------------------
/**
* Removes a single permission from all groups.
*
* #param int $permissionId
*
* #return mixed
*/
public function removePermissionFromAllGroups(int $permissionId)
{
return $this->db->table('auth_groups_permissions')
->where('permission_id', $permissionId)
->delete();
}
}
<?php
/*
* Core Auth routes file.
*/
$routes->group('api', ['namespace' => 'Modules\Auth\Controllers'], function ($routes) {
$routes->resource('group', ['filter' => 'authJwt']);
$routes->resource('permission', ['filter' => 'authJwt']);
$routes->resource('groupPermission', ['filter' => 'authJwt']);
$routes->resource('userPermission', ['filter' => 'authJwt']);
$routes->group('auth', function ($routes) {
$routes->post('signin-jwt', 'Auth::signInJwt', ['filter' => 'isSignIn']);
$routes->post('signin', 'Auth::signIn', ['filter' => 'isSignIn']);
$routes->get('signout', 'Auth::signOut', ['filter' => 'authJwt']);
$routes->get('is-signin', 'Auth::isSignIn',['filter' => 'authJwt']);
$routes->post('signup', 'Auth::signUp', ['filter' => 'isSignIn']);
$routes->post('forgot', 'Auth::forgot', ['filter' => 'isSignIn']);
$routes->post('reset-password-email', 'Auth::resetPasswordViaEmail', ['filter' => 'isSignIn']);
$routes->post('reset-password-sms', 'Auth::resetPasswordViaSms', ['filter' => 'isSignIn']);
$routes->post('activate-account-email', 'Auth::activateAccountViaEmail', ['filter' => 'isSignIn']);
$routes->post('send-activate-email', 'Auth::sendActivateCodeViaEmail', ['filter' => 'isSignIn']);
$routes->post('activate-account-sms', 'Auth::activateAccountViaSms', ['filter' => 'isSignIn']);
$routes->post('send-activate-sms', 'Auth::sendActivateCodeViaSms', ['filter' => 'isSignIn']);
});
});

Laravel 5.3 with mamp 4.2.2 (nginx) gives 200 HTTP status instead 422 when request validation fails

I have a simple ajax request on frontend
$.ajax({
url: '/api/marketing-research',
dataType: 'json',
type: 'post',
data: this.form.data(),
success(resp) {
console.log(resp);
}
});
And simple handler on backend
public function store(MarketingResearchRequest $request)
{
$research = Auth::user()->addMarketingResearch($request->castAll());
return $this->respond([
'type' => 'store marketing research',
'message' => 'Marketing Research successfully store.',
'id' => $research['id'],
'routeEdit' => route('services.marketingResearch.card', ['marketingResearch' => $research['id']]),
]);
}
As you see, here is used request with validation, so if i don't pass validation, i'm expecting an error with code 422 and json response with error messages.
BUT i get 200 HTTP status OK with html/text header and errors. On production server it works properly with the same code. So, where am i wrong?
MarketingResearchRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Media101\Request\Cast\Castable;
class MarketingResearchRequest extends FormRequest
{
use Castable;
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|max:200',
'target' => 'max:200',
'description' => 'string',
'started_at' => 'required|date',
'count_respond' => 'required|integer|min:1',
'price' => 'required|numeric|min:10',
'sum' => 'numeric',
'status' => 'integer',
'striations' => 'array',
'striations.*.fields.',
'striations.*.fields.volume' => 'required|numeric|min:0|max:100|nullable',
'striations.*.fields.gender' => 'string|max:10|nullable',
'striations.*.fields.ageFrom' => 'numeric|min:0|max:150|nullable',
'striations.*.fields.ageOn' => 'numeric|min:0|max:150|nullable',
'striations.*.fields.education' => 'string|max:40|nullable',
'striations.*.fields.ideology' => 'string|max:40|nullable',
'striations.*.fields.family_status' => 'string|max:40|nullable',
'striations.*.fields.children' => 'boolean|nullable',
'striations.*.fields.childrenCount' => 'numeric|max:100|nullable',
'striations.*.fields.incomeFrom' => 'numeric|nullable',
'striations.*.fields.incomeOn' => 'numeric|nullable',
'striations.*.fields.politics' => 'string|max:40|nullable'
];
}
protected function casts()
{
return [
'target' => 'null',
'started_at' => 'null',
'count_respond' => 'null',
'price' => 'null',
'sum' => 'null',
'status' => 'null',
];
}
}
Castable trait
<?php
namespace Media101\Request\Cast;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
/**
* Allows request to be able to cast it's parameters to desired types.
*
* #example
*
* // In request model
* public function casts()
* {
* return [
* 'birthed_at' => ['date', 'd.m.Y'],
* 'address' => 'null'
* ];
* }
*
* // In controller
* $model->update($request->castAll());
*
* Available casts:
* * date($format) - Casts to Carbon object using given format
* * null() - Casts empty string to null
*
* #mixin Request
*/
trait Castable
{
/**
* Override this method to define which attributes should this request cast
*
* #return array Indexed by field name, with value being array of cast name and case function arguments
*/
abstract protected function casts();
/**
* Extract all parameters and cast them
*
* #return array
*/
public function castAll()
{
return $this->castData($this->all());
}
/**
* Extract only specified parameter values and cast them
*
* #param sting[] $fields
* #return array
*/
public function castOnly($fields)
{
return $this->castData($this->only($fields));
}
/**
* Extract all the parameters except specified and cast them
*
* #param string[] $fields
* #return array
*/
public function castExcept($fields)
{
return $this->castData($this->except($fields));
}
/**
* Extract subarray from field and casts all the values there
*
* #param string $field
* #return array
*/
public function castNested($field)
{
return $this->castData($this->input($field, []));
}
/**
* Extract input value and casts it
*
* #param string $field
* #return mixed
*/
public function castInput($field, $default = null)
{
$casts = $this->casts();
return isset($casts[$field]) && $this->exists($field)
? $this->castValue($this->input($field, $default), $casts[$field])
: $this->input($field, $default);
}
/**
* #param array $data
* #return array
*/
protected function castData($data)
{
foreach ($this->casts() as $attribute => $cast) {
if (isset($data[$attribute]) || array_key_exists($attribute, $data)) {
$data[$attribute] = $this->castValue(#$data[$attribute], $cast);
}
}
return $data;
}
/**
* #param mixed $value
* #param array|string|callback $cast
* #return mixed
*/
protected function castValue($value, $cast)
{
if (!is_string($cast) && is_callable($cast)) {
return $cast($value);
} else {
$args = (array) $cast;
$method = array_shift($args);
array_unshift($args, $value);
return call_user_func_array([$this, 'castTo' . Str::camel($method)], $args);
}
}
// The cast methods
/**
* #param $input
* #param string $format
* #return Carbon|null
*/
protected function castToDate($input, $format)
{
return !isset($input) || $input === '' ? null : Carbon::createFromFormat($format, $input);
}
/**
* #param string $input
* #return string|null
*/
protected function castToNull($input)
{
return $input === '' ? null : $input;
}
}

How to get session data and put in a dropDownList in Yii 2?

I'm new in StackOverflow and also new using the framework Yii 2, and I need to get session data and put in a create and update form using the _form.php from a view called Planficacion, but when I try to use this line of code in the form:
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?>
Return this error: PHP Warning – yii\base\ErrorException. Invalid argument supplied for foreach()
I need to get the value of 'nombreProfesor' from a model called Profesor, and the relation of both Planificacion and Profesor is 'rutProfesor' and I want to show in the dropDownList only the 'nombreProfesor' of the actual session.
There are the codes from:
Profesor Model (Profesor.php)
<?php
namespace common\models;
use Yii;
class Profesor extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rutProfesor'], 'required'],
[['nombreProfesor', 'apellidoProfesor', 'escuelaProfesor'], 'string', 'max' => 45],
[['rutProfesor', 'claveProfesor'], 'string', 'max' => 15],
[['rol'], 'string', 'max' => 2],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'nombreProfesor' => 'Nombre Profesor',
'apellidoProfesor' => 'Apellido Profesor',
'escuelaProfesor' => 'Escuela',
'rutProfesor' => 'Rut',
'claveProfesor' => 'Clave Profesor',
'rol' => 'Rol',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPlanificacions()
{
return $this->hasMany(Planificacion::className(), ['rutProfesor' => 'rutProfesor']);
}
}
Planificacion Model (planificacion.php)
<?php
namespace common\models;
use Yii;
class Planificacion extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'planificacion';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['fecha', 'fechaRevision', 'fechaPlanificacion'], 'safe'],
[['objetivosPlanificacion', 'actividad1', 'actividad2', 'actividad3', 'actividad4', 'obsActividad1', 'obsActividad2', 'obsActividad3', 'obsActividad4', 'contenidoActividad1', 'contenidoActividad2', 'contenidoActividad3', 'contenidoActividad4'], 'string'],
[['rutProfesor'], 'string', 'max' => 15],
[['nombreSesion', 'recursosUtilizadosPlanificacion', 'estadoActividad1', 'estadoActividad2', 'estadoActividad3', 'estadoActividad4', 'evalActividad1', 'evalActividad2', 'evalActividad3', 'evalActividad4', 'nombreSupervisor', 'asistencia'], 'string', 'max' => 255],
[['estado', 'rutSupervisor'], 'string', 'max' => 30],
[['rutProfesor'], 'exist', 'skipOnError' => true, 'targetClass' => Profesor::className(), 'targetAttribute' => ['rutProfesor' => 'rutProfesor']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idPlanificacion' => 'Id Planificacion',
'rutProfesor' => 'Nombre Profesor',
'fecha' => 'Fecha',
'nombreSesion' => 'Nombre Sesion',
'objetivosPlanificacion' => 'Objetivos Planificacion',
'recursosUtilizadosPlanificacion' => 'Recursos Utilizados Planificacion',
'actividad1' => 'Actividad1',
'actividad2' => 'Actividad2',
'actividad3' => 'Actividad3',
'actividad4' => 'Actividad4',
'estadoActividad1' => 'Estado Actividad1',
'estadoActividad2' => 'Estado Actividad2',
'estadoActividad3' => 'Estado Actividad3',
'estadoActividad4' => 'Estado Actividad4',
'obsActividad1' => 'Obs Actividad1',
'obsActividad2' => 'Obs Actividad2',
'obsActividad3' => 'Obs Actividad3',
'obsActividad4' => 'Obs Actividad4',
'contenidoActividad1' => 'Contenido Actividad1',
'contenidoActividad2' => 'Contenido Actividad2',
'contenidoActividad3' => 'Contenido Actividad3',
'contenidoActividad4' => 'Contenido Actividad4',
'evalActividad1' => 'Eval Actividad1',
'evalActividad2' => 'Eval Actividad2',
'evalActividad3' => 'Eval Actividad3',
'evalActividad4' => 'Eval Actividad4',
'estado' => 'Estado',
'fechaRevision' => 'Fecha Revision',
'rutSupervisor' => 'Rut Supervisor',
'fechaPlanificacion' => 'Fecha Planificacion',
'nombreSupervisor' => 'Nombre Supervisor',
'asistencia' => 'Asistencia',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAsistencias()
{
return $this->hasMany(Asistencia::className(), ['idPlanificacion' => 'idPlanificacion']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRutProfesor0()
{
return $this->hasOne(Profesor::className(), ['rutProfesor' => 'rutProfesor']);
}
}
User Model (User.php)
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_SUPERVISOR = 1;
const ROL_PROFESOR = 2;
public $authKey;
/** #inheritdoc
/**
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($claveProfesor)
{
return $this->claveProfesor === $claveProfesor;
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public function isUserSimple($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 2]))
{
return true;
} else {
return false;
}
}
public function isUserAdmin($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 1]))
{
return true;
} else {
return false;
}
}
}
Planificacion Controller (planificacionController.php)
<?php
namespace frontend\controllers;
use Yii;
use common\models\Planificacion;
use common\models\PlanificacionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PlanificacionController implements the CRUD actions for Planificacion model.
*/
class PlanificacionController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Planificacion models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PlanificacionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Planificacion model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Planificacion model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Planificacion();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Planificacion model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Planificacion model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Planificacion model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Planificacion the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Planificacion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
First, why you getting the error, is because ArrayHelper::getValue() require an array as first parameter, as it's purpose is to
Retrieves the value of an array element or object property with the
given key or property name.
And Yii::$app->user->identity->rutProfesor wouldn't yield an array, no, it would yield an single string, which is current rutProfessor in the session.
Then, on how you create the dropDownList you wanted, i suggest using an ArrayHelper::map() which is more straightfoward.
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([
'rutProfesor' => Yii::$app->user->identity->rutProfesor
])->all(), 'rutProfesor', 'nombreProfesor'); ?>
I beleive that code will do you good.
Happy coding. :)

Pass array parameter from controller to Mailable class. Laravel

I am trying to send email after user successfully register. so right now i am stuck to pass data in email template.I am sending email with Mailable . so from my Register Controller i using like that Mail::to('example#email.com','User Name')->send(new Verify_Email())
So my question is how to pass array param into new Verify_Email()Massage build class.and so then how to pass from Verify_Email to View.
RegisterController.php
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$confirmation_code = str_random(30);
$user = User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => $confirmation_code
]);
$email_data = ([
'name' => $data['firstname'].' '.$data['lastname'],
'link' => '#'
]);
Mail::to('example#email.com','User Name')->send(new Verify_Email());
return $user;
}
Verify_Email.php
class Verify_Email extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user');
//--------------------------> **Send data to view**
//->with([
//'name' => $this->data->name,
//'link' => $this->data->link
//]);
}
Please follow this approach
Pass the inputs to the Verify_Email constructor and use $this->variable to pass them onto the view.
Mail::to('example#email.com','User Name')->send(new Verify_Email($inputs))
and then this in Verify_Email
class Verify_Email extends Mailable {
use Queueable, SerializesModels;
protected $inputs;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($inputs)
{
$this->inputs = $inputs;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('example#example.com')
->view('emails.verify-user')
->with([
'inputs' => $this->inputs,
]);
}
}
Hope that answers your question :)

Symfony Doctrine Many to Many insert CollectionType

I have a problem with my entities and controllers in Symfony. I would insert on my DB value in a many to many table generated.
Entity Requests with only many to many elements
class Requests {
/**
* #ORM\ManyToMany(targetEntity="Tipi", inversedBy="requests")
* #ORM\JoinTable(name="tipi_richieste")
*/
private $tipi;
public function __construct() {
$this->tipi = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add tipi
*
* #param \AppBundle\Entity\Tipi $tipi
*
* #return Requests
*/
public function addTipi(\AppBundle\Entity\Tipi $tipi) {
$this->tipi[] = $tipi;
return $this;
}
/**
* Remove tipi
*
* #param \AppBundle\Entity\Tipi $tipi
*/
public function removeTipi(\AppBundle\Entity\Tipi $tipi) {
$this->tipi->removeElement($tipi);
}
/**
* Get tipi
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTipi() {
return $this->tipi;
}
}
Entity Tipi with only many to many elements
class Tipi {
/**
* #ORM\ManyToMany(targetEntity="Requests", mappedBy="tipi")
*/
private $requests;
/**
* Constructor
*/
public function __construct() {
$this->requests = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add request
*
* #param \AppBundle\Entity\Requests $request
*
* #return Tipi
*/
public function addRequest(\AppBundle\Entity\Requests $request)
{
$this->requests[] = $request;
return $this;
}
/**
* Remove request
*
* #param \AppBundle\Entity\Requests $request
*/
public function removeRequest(\AppBundle\Entity\Requests $request)
{
$this->requests->removeElement($request);
}
/**
* Get requests
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRequests()
{
return $this->requests;
}
}
The Form type for insert is a CollectionType
->add('tipi', CollectionType::class, array(
'entry_type' => TipiType::class,
'allow_add' => true,
'prototype' => true,
'entry_options' => array(
'required' => true,
'label' => false,
)
))
And TipiType is an EntityType
->add('tipi', EntityType::class, array(
'label' => 'Tipo',
'class' => 'AppBundle:Tipi',
'attr' => array('class' => 'form-control'),
'by_reference' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('t');
},
))
And in my controller I work in this way:
public function indexAction(Request $request) {
$requests = new Requests();
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(RequestsType::class, $requests);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$requests->setCreateAt(new \DateTime('now'));
$em->persist($requests);
$em->flush();
return $this->redirectToRoute('requests_edit', array('id' => $requests->getId()));
}
return $this->render('AppBundle:Requests:index.html.twig', array(
'requests' => $requests,
'form' => $form->createView(),
));
}
When I put die for return the value of $form["tipi"]->getData() I get an array collection : Doctrine\Common\Collections\ArrayCollection#000000005b52ae6b00000000731dd0b4
But I get this error:
Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "AppBundle\Entity\Requests#$tipi", got "AppBundle\Entity\Requests" instead.
You need to do a foreach for this,
sample:
foreach $form->get("tipi")->getData() as $variableName) {
//Here you just need the setter for each data from its own entity
->$manager
->setEntity(variableName)
// your entity tipi
}
then after that you flush it from you main transaction or entity, it will automatically insert all data from collection.

Categories