how to remove data object from reponse coming from laravel fractol library? - php

I am getting data as an object in response from laravel fractal library by default for all APIs.
I don't want data instead I want some custom name instead of data but I am not able to do that.
How to customize the code from the fractal library to get the item instead of data.

Create DataSerializer Class:
namespace App\{Your Project Name}\Serializers;
use League\Fractal\Serializer\ArraySerializer;
class DataSerializer extends ArraySerializer
{
public function collection($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
public function item($resourceKey, array $data)
{
if ($resourceKey) {
return [$resourceKey => $data];
}
return $data;
}
}
Add setResponseData function in Base Controller:
public function setResponseData($default=true, $data, $transformer, $includes = null){
if($default){
$resource = fractal($data, $transformer);
if($includes){
$resource->parseIncludes($includes);
}
return $resource;
}
$resource = null;
if($data instanceof LengthAwarePaginator){
$dataCollection = $data->getCollection();
$resource = new Collection($dataCollection, $transformer, 'data');
$resource->setPaginator(new IlluminatePaginatorAdapter($data));
} elseif($data instanceof \Illuminate\Database\Eloquent\Collection){
$resource = new Collection($data, $transformer, 'data');
} elseif($data instanceof Model){
$resource = new Item($data, $transformer, 'data');
} else{
return [];
}
$manager = new Manager();
$manager->setSerializer(new DataSerializer());
if($includes){
$manager->parseIncludes($includes);
}
$content = [];
if($resource){
$content = $manager->createData($resource)->toArray();
}
return $content;
}
Call setResponseData function from your Derived Controller:
$response = $this->setResponseData(false, $data, new YourTransformer(), ['include-1']);

Related

Array to string conversion error -Slim Twig-

Setup: I have a slim application and I pulled in Illuminate DB and Twig view.
if (!$validator->passed()) {
$errors = $validator->errors();
$users = User::all();
return $this->view($response, 'auth.login', compact('errors','users'));
}
Problem: When I run the above code, I am able to retrieve the users variable in my view, but the errors variable throws the following error.
Notice: Array to string conversion in /Users/davidchen/Documents/sites/slim.com/vendor/twig/twig/lib/Twig/Environment.php(378) : eval()'d code
on line
70 Array
The errors variable returns a multidimensional array, below you'll find the result that I get from print_r($errors).
Array (
[username] => Array (
[0] => username already exists
)
[password] => Array (
[0] => password must consist of at least 6 characters
)
)
Here are my related project files:
Twig Setup File (app.php)
$c = $app->getContainer();
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($config['config']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
$c['db'] = function($c) use ($capsule){
return $capsule;
};
$c['view'] = function($c){
$options['cache']=false;
$view = new \Slim\Views\Twig(__DIR__."/../views", $options);
$view->addExtension(new \Slim\Views\TwigExtension(
$c->router,
$c->request->getUri()
));
$view->getEnvironment()->addGlobal('flash', $c->flash);
return $view;
};
$c['flash'] = function($c){
return new Slim\Flash\Messages();
};
Validator Class
namespace App\Models\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;
use Carbon\Carbon;
use DateTime;
class Validator extends Model
{
protected $field_name,
$data,
$errors = [];
/*
* Main validator
*/
public function __construct($request, $fields = []){
$data = $request->getParams();
$this->data = $data;
foreach ($fields as $field => $constraints) {
$this->field_name = $field;
if (isset($data[$field])) {
$field_value = $data[$field];
foreach (explode("|", $constraints) as $constraint) {
$obj = explode(":", $constraint);
$function_name = $obj[0];
if (isset($obj[1])) {
if(method_exists($this, $function_name))
{
$this->$function_name($obj[1],$field_value);
}
}
}
}else{
if (strpos($constraints, 'required') !== false) {
$validator->report($validator->field_name.' field is requried');
}
}
}
return $this;
}
/*
* Object Interface Methods
*/
private function report($message){
$this->errors[$this->field_name][]= $message;
}
public function errors(){
return $this->errors;
}
public function passed(){
if (!count($this->errors)) {
return true;
}
}
/*
* Validation Rules
*/
public function max($length,$value){
if (strlen($value)>$length) {
$this->report("{$this->field_name} must consist of less than {$length} characters");
}
}
public function min($length,$value){
if (strlen($value)<$length) {
$this->report("{$this->field_name} must consist of atleast {$length} characters");
}
}
public function distinct($tableName,$value){
if (DB::table($tableName)->where($this->field_name, $value)->exists()) {
$this->report("{$this->field_name} already exists");
}
}
public function date($format,$date){
if (!preg_match("/\d{4}-\d{2}-\d{2}\b/",$date)) {
$this->report("incorrect {$this->field_name} values");
}else{
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) !== $date) {
$this->report("{$this->field_name} format should be {$format}");
}
}
}
public function match($matchField,$value){
if (isset($this->data[$matchField])) {
$valueTwo = $this->data[$matchField];
if ($value !== $valueTwo) {
$this->report("{$this->field_name} does not match {$matchField}");
}
}else{
$this->report("{$matchField} is required");
}
}
public function format($type,$value){
switch ($type) {
case 'noWhiteSpace':
if (preg_match("/\s/",$value)) {
$this->report("{$this->field_name} may not contain any spaces");
}break;
case 'alpha':
if (preg_match("/[^a-zA-Z]/",$value)) {
$this->report("{$this->field_name} may only contain letters");
}break;
case 'alphaNum':
if (preg_match("/[^a-zA-Z0-9]/",$value)) {
$this->report("{$this->field_name} may only contain letters");
}break;
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->report("in correct {$this->field_name} format");
}break;
default:
# code...
break;
}
}
}
Base Controller
namespace App\Controllers;
/**
*
*/
class Controller
{
protected $c;
function __construct($container)
{
$this->c = $container;
}
public function view($response, $path,$variables = []){
$this->c->view->render($response, str_replace(".","/",$path).".twig", $variables);
}
public function pathFor($routeName,$data = []){
return $this->c->router->pathFor($routeName,$data);
}
}
Auth Controller
namespace App\Controllers\Auth;
use App\Models\User\User;
use App\Controllers\Controller;
use App\Models\Auth\Validator;
/**
*
*/
class AuthController extends Controller
{
public function getLogin($request, $response){
return $this->view($response, 'auth.login');
}
public function postLogin($request, $response){
$validator = new Validator($request,[
'username'=>'required|min:3|max:64|format:alphaNum|distinct:users',
'password'=>'required|min:6|max:64|',
]);
if (!$validator->passed()) {
$errors = $validator->errors();
$users = User::all();
return $this->view($response, 'auth.login', compact('errors','users'));
}
return $this->view($response, 'home.login');
}
}
login.twig file
login.twig file
Hope one of you can shed some light on this problem. I've been struggling with this all morning.
You could try to loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
Read more

Insert a new record if not exist and update if exist Laravel 5.3

Here's my configController code :
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Config;
}
else{
$obj = Config::firstOrNew(array('id' => Input::get('id')));
$obj->save();
}
return $this->saveHandler($request, $obj);
}
}
it didn't work, any idea ?

ZF2 bind form data

I am trying to bind the form data before I set the edited form data as I don't want to lose values which hasn't be changed. It actually throws me an error and the ZF2 website doesn't provide me a good working example. I am stuck and I don't want to wrote a dirty workaround, someone? :)
I've created a model as follow:
namespace Application\Model;
class Advertisement {
public $id;
public $name;
public $code;
public $banner;
public $fileupload;
public function exchangeArray($data)
{
$this->id = isset($data['id']) ? $data['id'] : null;
$this->name = isset($data['name']) ? $data['name'] : null;
$this->code = isset($data['code']) ? $data['code'] : null;
$this->banner = isset($data['banner']) ? $data['banner'] : '';
$this->fileupload = isset($data['fileupload']) ? $data['fileupload'] : '';
}
public function exchangeJsonToPhpArray($json)
{
}
public function getArrayCopy()
{
return get_object_vars($this);
}
}
My Controller;
public function editAction()
{
# Get Request and Params
$request = $this->getRequest();
$language = $this->params('language');
$id = $this->params('id');
# Get advertisement data
$oAdvertisement = new Advertisement();
if (!$oAdvertisement = $this->getAdvertisementTable()->selectAdvertisementToEdit(array('id' => $id)))
return $this->redirect()->toRoute('admin/advertisement');
# Advertisement form
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$form = new AdvertisementForm($dbAdapter, $this->params('language'));
$form->bind($oAdvertisement);
# Post request
$request = $this->getRequest();
if ($request->isPost()) {
# Set post data
$post = array_merge_recursive($this->request->getPost()->toArray(), $this->request->getFiles()->toArray());
$form->setData($post);
# Validate form
if ($form->isValid()) {
# Get form data
$formData = $form->getData();
Debug::dump($form->getData());
# Get service config
$serviceLocator = $this->getServiceLocator();
$config = $serviceLocator->get('config');
$sBannerName = $config['banner_upload_path'] . '/' . md5(mt_rand()) .'.jpg';
# Insert into database
$oAdvertisement->exchangeArray($formData);
# Validate and rename image upload
//.. image upload
Debug::dump($oAdvertisement);
exit;
# Update database record
$this->getAdvertisementTable()->updateAdvertisement($oAdvertisement, $id);
// success..
} else {
// false..
}
}
# Return view model
return new ViewModel(array(
'form' => $form,
));
}
Error;
Fatal error: Cannot use object of type Application\Model\Advertisement as array in ..../module/Application/src/Application/Model/Advertisement.php on line 29
In exchangeArray () method try to test the type of the parameter $ data.
Personally, I put systematically:
if ($data instanceof IteratorAggregate) {
$data = iterator_to_array($data->getIterator(), true);
} elseif ($data instanceof Iterator) {
$data = iterator_to_array($data, true);
} elseif (! is_array($data)) {
throw new Exception(_('Data provided is not an array, nor does it implement Iterator or IteratorAggregate'));
}

php variable delegate functions

I have the following code and am trying to find a solution:
<?php
class t1 {
public $response = array();
public $request = array();
public function getRequest() {
return $this->request;
}
public function getResponse() {
return $this->response;
}
}
class t2 extends t1 {
public function run($f) {
$this->response = $f($this);
return $this;
}
}
$delegate = function($c)
{
// PLACEHOLDER
// This is the only place to update test code
// It's not allowed to modify any other section of this code
};
$t = new t2();
print_r(array("request" => $t->run($delegate)->getRequest(), "response" => $t->getResponse()));
?>
I assume $delegate is a dynamic function. Anyone able to walk me through this.
I'm thinking in PLACEHOLDER is should be:
I assume $delegate is a dynamic function.
Yes. $delagate is a PHP Closure.
If you define your function as:
$delegate = function($c)
{
};
and pass it to $t->run, then $c will be the $t instance.

PHP array is null after passing to function

So I have a problem I have an array that is passes to setData function
after that I call getE that suppose to return the array but instead I'm getting Null what am I doing wrong?
<?php
class Se {
public $data1;
public function setData(array $data){
if (empty($data)) {
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
}
public function getE(){
return $data1[0];
}
}
$tmpaaa= array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
So my revised code looks like this now
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = $data;
}
public function getE()
{
return $this->$data1[0];
}
};
$tmpaaa= array('3','2');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
?>
In order to access class instance properties from within the class, you need to prefix the variable name with $this. See http://php.net/manual/language.oop5.properties.php
To fix your problem, change this in setData
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
to this
$this->data1 = array_values($data);
var_dump($this->data1);
and getE to
public function getE(){
return $this->data1[0];
}
Update
As it appears the $data1 property is required in Se, I'd set it in the constructor, eg
public function __construct(array $data) {
$this->setData($data);
}
and instantiate it with
$ttt = new Se($tmpaaa);
echo $ttt->getE();
It is also recommended not closing the php tag in a class file, this prevents space issues.
<?php
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = array_values($data); //you error was here, no need to to assign $data twice so I deleted top line.
}
public function getE()
{
return $this->data1[0];
}
}
$tmpaaa = array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();

Categories