Laravel override renderer view - php

I would like that as soon as an ajax request is sent where there is view ('view') instead of returning the raw view its returns a JSON
Like that:
/**
* #param \Illuminate\Contracts\View\View $view
* #return \Illuminate\Http\JsonResponse
*/
protected function ajaxResponse (View $view)
{
return response()->json([
'id' => $view->getData()['page'],
'title' => $view->getData()['title'],
'content' => $view->renderSections()['content'],
'replacepage' => null,
]);
}
But I absolutely don't know how to do it I don't want to repeat myself in each controller
I have tried to replace View with mine but it does not work as I would like everything to work but I cannot recover the section of my page
<?php
namespace App\Extensions\View;
use Illuminate\View\View;
class AjaxView extends View
{
/**
* Get the contents of the view instance.
*
* #return string
* #throws \Throwable
*/
protected function renderContents()
{
if(request()->ajax()) {
echo $this->getResponse($this->getData());
exit;
}
return parent::renderContents();
}
/**
* #param array $data
* #return false|string
*/
public function getResponse (array $data = [])
{
return json_encode([
'id' => $data['page'],
'title' => (!empty($data['title']) ? $data['title'] . ' - ' . config('app.name') : null),
'content' => $this->renderSections()['content'],
'replacepage' => null
]);
}
}
This returns:

Perhaps you can do it this way:
In app/Http/Controllers/Controller.php, add method response();
protected function view($viewPath, $content, $status = 200, array $headers = [])
{
if(request()->ajax()) {
return response()->json($content, $status, $headers);
}
return view($viewPath, $content);
}
Your controller methods can then use like this:
public function create()
{
// logic
return $this->view('view_path', $data);
}

I have change your function by
protected function ajaxView(string $viewPath, array $content = [], int $status = 200, array $headers = [])
{
$view = view($viewPath, $content);
if(request()->ajax()) {
dd($view->getData());
return response()->json([
'id' => $this->view->getData()['page'],
'title' => $this->view->getData()['title'],
'content' => $this->view->renderSections()['content'],
'replacepage' => null,
], $status, $headers);
}
return $view;
}
But the dd() record array is empty if i put my dd() outside of my if the record is not empty

Related

Empty data table symfony 3.4 to 4.4

I currently have a big problem on my Symfony project since I switched to version 4.4. My versioning was correctly done but I have a "Project" page that displays all the projects created in the website database. The problem is that the project creation is feasible and the projects are well displayed in the database but the site does not display them. I checked the code of my ProjectController and everything seems to be normal. However, I changed one line of it because the syntax for calling classes through the getRepository has changed between versions 3.4 and 4.4. Before, I used to call my classes by doing getRepository('App::$className') with a className variable whose value changed depending on the classes that were called on my page. Now a getRepository doesn't accept the 'App::' and so I had to define the path of my classes by setting getRepository('App::$className'). And I have the impression that the problem can come from here because maybe it only retrieves the first class called and doesn't go to the next one.
I can't solve the problem because it's not an error message, so I'm looking for a needle in a haystack. I don't have a lot of experience with symfony because I've never used this framework before, so I came up with this project that just needed an upgrade.
I put the code of my ProjectController just below to better understand my explanation.
<?php
namespace App\Controller;
use App\Entity\Advancement;
use App\Entity\Alert;
use App\Entity\Project;
use App\Entity\State;
use App\Form\Search\ProjectSearchType;
use App\Form\Type\AdvancementType;
use App\Form\Type\AlertType;
use App\Form\Type\ProjectType;
use App\Model\ProjectSearch;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ProjectController extends BaseController
{
protected function listAction($className, $params = array())
{
return array_merge(array(
'title' => 'title.' . $className . '.list',
'pagetitle' => 'title.' . $className . '.list',
$className . 's' => $this->getRepository('App\\Entity\\' . $className)->getList(),
), $params);
}
protected function createAction($request, $project, $form, $className)
{
if ($form->handleRequest($request)->isSubmitted() && $form->handleRequest($request)->isValid()) {
$entity = $form->getData();
$entity->setCreatedBy($this->getUser());
$entity->setCreatedAt(new \DateTime());
$this->persist($entity);
$this->flush();
$this->addFlash('success', 'flash.success.created.' . $className);
return $this->redirect($this->generateUrl('project_edit', array('id' => $project->getId())) . '#tab-' . $className);
}
return array(
'form' => $form->createView(),
'title' => $this->trans('title.' . $className . '.create'),
'pagetitle' => $this->trans('title.' . $className . '.create'),
'projectLink' => $this->generateUrl('project_edit', array('id' => $project->getId())),
);
}
protected function editAction($request, $project, $form, $className, $class)
{
if ($form->handleRequest($request)->isSubmitted() && $form->handleRequest($request)->isValid()) {
$entity = $form->getData();
$entity->setUpdatedBy($this->getUser());
$entity->setUpdatedAt(new \DateTime());
$this->flush();
$this->addFlash('success', 'flash.success.updated.' . $className);
return $this->redirect($this->generateUrl('project_edit', array('id' => $project->getId())) . '#tab-' . $className);
}
return array(
'form' => $form->createView(),
'title' => $this->trans('title.' . $className . '.edit', array('%name%' => $class)),
'pagetitle' => $this->trans('title.' . $className . '.edit', array('%name%' => $class)),
'projectLink' => $this->generateUrl('project_edit', array('id' => $project->getId())),
);
}
protected function deleteAction($class, $className)
{
try {
$this->remove($class);
$this->flush();
$this->addFlash('success', 'flash.success.deleted.' . $className);
} catch (ForeignKeyConstraintViolationException $e) {
$this->addFlash('error', 'flash.error.deleted.' . $className);
}
if ($className != 'project') {
$id = $class->getProject()->getId();
$route = $this->generateUrl('project_edit', array('id' => $id)) . '#tab-' . $className;
} else {
$route = $this->generateUrl('project_list');
}
return $this->redirect($route);
}
/**
* #Route("/projects/{page}", defaults={"page":1}, name="project_list")
* #Template("Project\listProject.html.twig")
* #Security("has_role('ROLE_READER')")
*/
public function projectListAction(Request $request, $page = 1)
{
$searchModel = new ProjectSearch();
if (!$this->isGranted('ROLE_READER')) {
$searchModel->setCompany($this->getUser()->getCompany());
}
$searched = $searchModel;
$searchForm = $this->get('form.factory')->createNamed('', ProjectSearchType::class, $searchModel, array(
'method' => 'GET',
'action' => $this->generateUrl('project_list') . '#results',
));
$searchForm->handleRequest($request);
if ($searchForm->isSubmitted() && $searchForm->isValid()) {
$searched = $searchForm->getData();
}
$pager = $this->getPager($page, $this->getRepository(Project::class)->getSearchQuery($searched), $searchModel->getPerPage());
return $this->listAction('project', array(
'pager' => $pager,
'projects' => $pager->getCurrentPageResults(),
'searchForm' => $searchForm->createView(),
));
}
/**
* #Route("/project/new",name="project_create")
* #Template("Project\createProject.html.twig")
* #Security("has_role('ROLE_READER')")
*/
public function projectCreateAction(Request $request)
{
$project = new Project();
$project->setBeginAt(new \DateTime());
$project->setState($this->getRepository(State::class)->find(State::INITIALIZED));
$project->setCompany($this->getUser()->getCompany());
$form = $this->createForm(ProjectType::class, $project, array(
'mode' => 'create',
'display_company_select' => $this->isGranted('ROLE_SUPERADMIN'),
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$project = $form->getData();
$project->setCreatedBy($this->getUser());
$this->persist($project);
$this->flush();
$this->addFlash('success', 'flash.success.created.project');
return $this->redirect($this->generateUrl('project_list'));
}
return array(
'modeEdit' => false,
'form' => $form->createView(),
'title' => $this->trans('title.project.create'),
'pagetitle' => $this->trans('title.project.create'),
'project' => $project,
);
}
/**
* #Route("/project/edit/{id}", name="project_edit")
* #Template("Project\createProject.html.twig")
* #Security("is_granted('edit', project)")
*/
public function projectEditAction(Request $request, Project $project)
{
$project = $this->getManager(Project::class)->initForEdition($project);
$form = $this->createForm(ProjectType::class, $project, array(
'display_company_select' => $this->isGranted('ROLE_SUPERADMIN'),
));
try {
$alerts = $this->getRepository(Alert::class)->getAlertsByProject($project);
} catch (Exception $e) {
$alerts = array(new Alert());
}
try {
$advancements = $this->getRepository(Advancement::class)->getAdvancementsByProject($project);
} catch (Exception $e) {
$advancements = array(new Advancement());
}
if ($form->handleRequest($request)->isSubmitted() && $form->handleRequest($request)->isValid()) {
$project = $this->getManager(Project::class)->updateProject($form->getData());
$this->flush();
$this->addFlash('success', 'flash.success.updated.project');
return $this->redirect($this->generateUrl('project_list'));
}
return array(
'modeEdit' => true,
'form' => $form->createView(),
'advancements' => $advancements,
'alerts' => $alerts,
'title' => $this->trans('title.project.edit', array('%name%' => $project)),
'pagetitle' => $this->trans('title.project.edit', array('%name%' => $project)),
'project' => $project,
);
}
/**
* #Route("/project/view/{id}", name="project_view")
* #Template("viewProject.html.twig")
* #Security("is_granted('view', project)")
*/
public function projectViewAction(Request $request, Project $project)
{
return $this->projectEditAction($request, $project);
}
/**
* #Route("/project/delete/{id}", name="project_delete")
*/
public function projectDeleteAction(Request $request, Project $project)
{
// #todo : voir le delete en cascade
return $this->deleteAction($project, 'project');
}
/**
* #Route("/project/print", name="project_print")
*/
public function projectPrintAction(Request $request)
{
$projects = $this->getRepository(Project::class)->findById(array_keys($request->request->all()));
$html = '';
foreach ($projects as $project) {
$html .= $this->renderView('resume.html.twig', array(
'project' => $project,
));
}
if ($html == '') {
$this->addFlash('error', 'warn.project.check');
return $this->redirect($this->generateUrl('project_list'));
}
// Génération du pdf
$html2pdf = $this->get('html2pdf_factory')->create();
$html2pdf->WriteHTML($html);
return new Response(
$html2pdf->Output(),
200,
array(
'Content-Type' => 'application/pdf; charset=utf-8',
)
);
}
/**
* #Route("/advancements",name="advancement_list")
* #Template("listAdvancement.html.twig")
*/
public function advancementListAction(Request $request)
{
return $this->listAction('advancement');
}
/**
* #Route("/advancement/new/{id}",name="advancement_create")
* #Template("createAdvancement.html.twig")
*/
public function advancementCreateAction(Request $request, Project $project)
{
$avancement = new Advancement();
$avancement->setProject($project);
$form = $this->createForm(AdvancementType::class, $avancement, array());
return $this->createAction($request, $project, $form, 'advancement');
}
/**
* #Route("/advancement/edit/{id}", name="advancement_edit")
* #Template("createAdvancement.html.twig")
*/
public function advancementEditAction(Request $request, Advancement $advancement)
{
$form = $this->createForm(AdvancementType::class, $advancement, array());
return $this->editAction($request, $advancement->getProject(), $form, 'advancement', $advancement);
}
/**
* #Route("/advancement/delete/{id}", name="advancement_delete")
*/
public function advancementDeleteAction(Request $request, Advancement $advancement)
{
return $this->deleteAction($advancement, 'advancement');
}
/**
* #Route("/alerts",name="alert_list")
* #Template("listAlert.html.twig")
*/
public function alertListAction(Request $request)
{
return $this->listAction('alert');
}
/**
* #Route("/alert/new/{id}",name="alert_create")
* #Template("createAlert.html.twig")
*/
public function alertCreateAction(Request $request, Project $project)
{
$alerte = new Alert();
$alerte->setProject($project);
$form = $this->createForm(AlertType::class, $alerte, array());
return $this->createAction($request, $project, $form, 'alert');
}
/**
* #Route("/alert/edit/{projectid}/{alertid}", name="alert_edit")
* #ParamConverter("project", class="Project", options={"id" = "projectid"})
* #ParamConverter("alert", class="Alert", options={"id" = "alertid"})
* #Template("createAlert.html.twig")
*/
public function alertEditAction(Request $request, Project $project, Alert $alert)
{
$form = $this->createForm(AlertType::class, $alert, array());
return $this->editAction($request, $project, $form, 'alert', $alert);
}
/**
* #Route("/alert/delete/{id}", name="alert_delete")
*/
public function alertDeleteAction(Request $request, Alert $alert)
{
return $this->deleteAction($alert, 'alert');
}
/**
* #Template("_projectLoads.html.twig")
*/
public function projectLoadsAction(Request $request, $projectId)
{
$project = $this->getManager(Project::class)->getProject($projectId);
$slippingCalendar = $this->get('date.handler')->slippingCalendar();
// Returned loads can be outside start-end, so we limit to this year
$validLoads = array();
foreach ($project->getLoads() as $l) {
$id = $l->getUser()->getId();
$year = $l->getYear();
if (!array_key_exists($id, $validLoads)) {
$validLoads[$id] = array('user' => $l->getUser());
}
$validLoads[$id][$year][] = $l;
}
$activities = $this->getActivitiesByMonth($project);
return array(
'project' => $project,
'loads' => $validLoads,
'activities' => $activities,
'slippingCalendar' => $slippingCalendar, // yyyy-11-01, yyyy-12-01, yyyy-01-01,...
);
}
/**
* Build an array with the project activies spread by month and year
* #param Project $project
* #return array
*/
protected function getActivitiesByMonth(Project $project)
{
$validActivities = array();
foreach ($project->getActivities() as $a) {
$id = $a->getUser()->getId();
$date = $a->getMondayDate();
$i = 0;
do {
$year = $date->format('Y');
$month = $date->format('m');
if (!array_key_exists($id, $validActivities)) {
$validActivities[$id] = array('user' => $a->getUser());
}
if (!array_key_exists($year, $validActivities[$id])) {
$validActivities[$id][$year] = array();
}
$validActivities[$id][$year][$month][] = $a->getTimeDay($i);
$date->modify('+1 day');
$i++;
} while ($i < 7);
}
return $validActivities;
}
}
I am looking to see the projects in the database reappear on my web page.
The table is empty, although it should be populated by the projects in the DB.

How to validate model object instance in Laravel?

I've got the following model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $guarded = ['id'];
public static function rules()
{
return [
'created_at' => 'nullable',
'updated_at' => 'nullable',
'name' => 'required|string|between:1,255',
'description' => 'required|string|between:1,255',
'date_added' => 'nullable',
'date_edited' => 'nullable',
'unit' => 'required|string|between:1,255',
'unit_type' => 'required|integer',
'stock' => 'nullable|string|between:0,255',
'barcode' => 'nullable|string|between:0,32',
'tax' => 'nullable|float',
'price' => 'nullable|float',
'category_id' => 'required|integer|gt:0'
];
}
}
And there's a controller ProductController that has an action insertProduct.
class class ProductController extends ApiController { // controller class
public function insertProduct(Request $request) {
$inputJson = $request->input('data_json', null);
if(empty($inputJson)) {
$inputJson = $request->getContent();
if(empty($inputJson)) {
return $this->errorResponse(
'Either data_json formdata parameter or request body should contain a JSON string.'
);
}
}
try {
$product = $this->extractProductFromJSON($inputJson);
} catch(\Exception $e) {
return $this->errorResponse($e->getMessage(), 400);
}
// When I dump the Product ($product) instance using dd(), it is just as expected and its
// properties contain the right values.
$validator = Validator::make($product, Product::rules());
/* Above line causes exception:
TypeError: Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type
array, object given,
called in /.../vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php
on line 261 in file /.../vendor/laravel/framework/src/Illuminate/Validation/Factory.php
on line 98
*/
if($validator->fails()) {
return $this->errorResponse($validator->errors()->first());
}
// ...
}
// How I extract the data from the JSON string (which is input).
// Although I don't think this has anything to do with my problem.
private function extractProductFromJSON(string $json) {
$data = \json_decode($json);
if(\json_last_error() != JSON_ERROR_NONE) {
throw new \Exception('Error parsing JSON: ' . \json_last_error_msg());
}
try {
$productData = $data->product;
$productId = empty($productData->id) ? null : $productData->id;
// Product id is allowed to be absent
$product = new Product(); // My \App\Product model instance.
$product->id = $productId;
$product->name = $productData->name;
$product->description = $productData->description;
$product->date_added = $productData->date_added;
$product->date_edited = $productData->date_edited;
$product->unit = $productData->unit;
$product->unit_type = $productData->unit_type;
$product->stock = $productData->stock;
$product->barcode = $productData->barcode;
$product->tax = $productData->tax;
$product->price = $productData->price;
$product->category_id = $productData->category_id;
return $product;
} catch(\Exception $e) {
echo 'EXCEPTION...';
}
}
} // end of controller class
It seems pretty clear there's something wrong with the following line:
$validator = Validator::make($product, Product::rules());
The simplest cause I can think of, is that the validator simply does not accept objects and only wants arrays.
If not, what could be the problem?
If Laravel's validation only works with arrays, is it somehow possible to validate an object?
validator = Validator::make($product, Product::rules());
the problem is not Product::rules() but $product. Product::rules() is correct because it's return an array, but $product is an object instead of an array. You should change/convert $product to an array an example:
validator = Validator::make((array)$product, Product::rules());
Yes! You're right. If we look at the make method, we can see that it accepts rules as an array.
* #param array $data
* #param array $rules
* #param array $messages
* #param array $customAttributes
* #return \Illuminate\Validation\Validator
* #static
*/
public static function make($data, $rules, $messages = [], $customAttributes = [])
{
/** #var \Illuminate\Validation\Factory $instance */
return $instance->make($data, $rules, $messages, $customAttributes);
}
I usually validate data directly in the controller
$validator = Validator::make($info, [
'shortDescription' => 'required',
'description' => 'required',
'countryId' => 'required',
'cities' => 'required | array | min:1',
]);
class Cliente extends Eloquent
{
public static $autoValidates = true;
protected static $rules = [];
protected static function boot()
{
parent::boot();
// or static::creating, or static::updating
static::saving(function($model)
{
if ($model::$autoValidates) {
return $model->validate();
}
});
}
public function validate()
{
}
}

How paginate result of http response with laravel livewire

I want to populate a table with calling HTTP request and fetch a JSON fine,
I set up live wire like this which can properly populate the table:
public function render()
{
$this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();
return view('livewire.line-index', ['lines' =>json_decode($this->response)])->layout('layouts.app', ['header' => 'Line Management']);
}
but when I add paginate like this:
public function render()
{
$this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();
return view('livewire.line-index', ['lines' =>json_decode($this->response)->paginate(25)])->layout('layouts.app', ['header' => 'Line Management']);
}
I see this error:
Call to a member function paginate() on array
Solution:
need to convert array to the collection and then creating a macro for using pagination on
collection.
public function render()
{
$this->response = Http::timeout(30)->get('http://127.0.0.1:8000/api/lines')->body();
$collection = collect(json_decode($this->response));
return view('livewire.line-index', ['lines' =>$collection->paginate(20)])->layout('layouts.app', ['header' => 'Line Management']);
}
For creating a macro you need to update the AppServiceProvider.php file:
<?php
namespace App\Providers;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
/**
* Paginate a standard Laravel Collection.
*
* #param int $perPage
* #param int $total
* #param int $page
* #param string $pageName
* #return array
*/
Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
}
Reference: https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

Laravel get data from db array not working

When I run the code I get no error but the data I am trying to display is not displaying it's just blank.. can someone tell me what I'm doing wrong?
My controller:
public function openingPage($id) {
$this->getGames();
$games = $this->getGames();
return view('caseopener')->with('games',$games);
}
private function getGames() {
$games = array();
foreach ($this->data->items as $item) {
$game = new Game($item);
$games[] = array(
'id' => $game['id'],
'name' => $game['name'],
'price' => $game['price'],
'image' => $game['image'],
);
}
return $games;
}
The 'Game' Model that is used in 'getGames function':
class Game extends Model
{
private $id;
public $data;
public function __construct($id) {
parent::__construct();
$this->id = $id;
$this->data = $this->getData();
}
private function getData() {
$game = DB::table('products')->where('id', 1)->first();
if(empty($game)) return array();
return $game;
}
}
The view:
#foreach ($games as $game)
<div class="gold">$ {{ $game['price'] }}</div>
#endforeach
I think you are over-complicating things. You could simplify your flow like this:
Given your provided code, it seems like you are using a custom table name ('products') in your Game model. So we'll address this first:
Game.php
class Game extends Model
{
protected $table = 'products'; //
}
Now, it seems like you're searching an array of Game ids ($this->data->items). If so, you could make use of Eloquent for your query, specially the whereIn() method:
YourController.php
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', $games);
}
Optionally, if you want to make sure of just returning the id, name, price and image of each Game/product, you could format the response with API Resources:
php artisan make:resource GameResource
Then in your newly created class:
app/Http/Resources/GameResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'image' => $this->image,
];
}
}
So now just update your controller:
YourController.php
use App\Http\Resources\GameResource;
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', GameResource::collection($games));
} // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Fractal API call does not return content

I worte some API methods with the fractal package to output content. When I call the specific resources, everything returns empty.
To check if everything is working I performed some prints of the content variables inbetween. For example, if I take the $incidents variable in the index function I get returned all entries in the database as expected.
The same is true, when I call the $collection variable in the respondWithCollection method in the API controller. The data is available here as well. But the browser output is only this:
{
"data": {
"headers": {}
}
}
To keep it simple, this is the method to show all results of a database:
class ApiIncidentsController extends ApiController {
protected $incidentTransformer;
protected $fractal;
function __construct(IncidentTransformer $incidentTransformer){
$this->incidentTransformer = $incidentTransformer;
$this->beforeFilter('auth.basic', ['on' => 'post']);
$this->fractal = new Manager();
parent::__construct($this->fractal);
}
public function index()
{
$incidents = Incident::all();
if( ! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
return $this->respond([
'data' => $this->respondWithCollection($incidents, new IncidentTransformer),
]);
}
}
The API controller managing these calls is this:
class ApiController extends Controller {
protected $statusCode = 200;
protected $fractal;
public function __construct(Manager $fractal) {
$this->fractal = $fractal;
}
public function getStatusCode() {
return $this->statusCode;
}
public function setStatusCode($statusCode) {
$this->statusCode = $statusCode;
return $this;
}
public function respond($data, $headers = []) {
return Response::json($data, $this->getStatusCode(), $headers);
}
protected function respondWithItem($item, $callback) {
$resource = new Item($item, $callback);
$rootScope = $this->fractal->createData($resource);
return $this->respondWithArray($rootScope->toArray());
}
protected function respondWithArray(array $array, array $headers = []) {
return Response::json($array, $this->statusCode, $headers);
}
protected function respondWithCollection($collection, $callback) {
$resource = new Collection($collection, $callback);
$rootScope = $this->fractal->createData($resource);
return $this->respondWithArray($rootScope->toArray());
}
Update 1
This is the IncidentTransformer:
use League\Fractal\TransformerAbstract;
class IncidentTransformer extends TransformerAbstract {
public function transform(Incident $incident) {
return [
'incidentReference' => $incident['incidentReference'],
'latitude' => $incident['latitude'],
'longitude' => $incident['longitude'],
'archived' => (boolean) $incident['incidentArchived']
];
}
}
Update 2
I tried something else, by removing the respond wrapper. Then everything is fine. But I want to use the respond function I wrote to abstract the code. This seems to be the issue. When I pass in the data into the function, nothing is being returned. When I dump the variable data, There is a JSON Response returned. But the respondWithCollection Method within returns an array. I don't see why this is happening. Could this be the issue?
I adapted the method like this:
public function index()
{
$incidents = Incident::all();
if( ! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
$data = $this->respondWithCollection($incidents, new IncidentTransformer);
return $this->respond([
'data' => $data
]);
}
}
But still the output is empty. So it must be something with the response function.
You are returning Response::json() twice.
$this->respond returns Response::json, but also $this->respondWithCollection() returns respondWithArray() which also does.
Try something like:
public function index()
{
$incidents = Incident::all();
if( ! $incidents) {
return Response::json([
'error' => [
'message' => 'There are no incidents in the database.',
'code' => 100
]
], 404);
} else {
// getCollection instead of respondWithCollection
$data = $this->getCollection($incidents, new IncidentTransformer);
return $this->respond([
'data' => $data
]);
}
}
-
// getCollection instead of respondWithCollection
protected function getCollection($collection, $callback) {
$resource = new Collection($collection, $callback);
$rootScope = $this->fractal->createData($resource);
// don't respond again
//return $this->respondWithArray($rootScope->toArray());
return $rootScope->toArray();
}

Categories