I have my controller with index() and show().
{
/**
* Display a listing of the resource.
*
* #return \App\Http\Resources\MyRessource
*/
public function index()
{
//???
}
/**
* Display the specified resource.
*
* #param \App\Models\Test $test
* #return \App\Http\Resources\TestRessource
*/
public function show(Test $test)
{
return new \App\Http\Resources\TestRessource($test);
}
}
In my resource the show() has the format I want for return, so the result for http://127.0.0.1/Test/1 is the ID 1 with the formatted JSON.
{
"data": {
"id": 1,
"ref": "0103573026466442101007175850",
"tax": null,
"date_in": "2021-10-08T12:37:05.000000Z",
"date_out": "2021-10-11T08:02:17.000000Z"
}
}
I want the index() to return the same way by using my resource.
When I do index() on http://127.0.0.1/Test, it returns all my data but not in the formatted JSON that I want.
Resource code:
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
"id" => $this->id,
"ref" => $this->ref,
"tax" => $this->tax,
"date_in" => $this->date_in,
"date_out" => $this->date_out
];
}
On index() do as in docs.
return TestRessource::collection(Test::all());
Related
I have 2 variables that I want to send to resource and show them via API like below:
return new RoomDetailResource($data_array, $sum);
and the resource I have written is like below:
class RoomDetailResource extends JsonResource
{
/**
* #var
*/
public $sum;
/**
* Create a new resource instance.
*
* #param mixed $resource
* #return void
*/
public function __construct($resource, $sum)
{
// Ensure you call the parent constructor
parent::__construct($resource);
$this->resource = $resource;
$this->sum = $sum;
}
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'sum' => $this->sum
];
}
}
now what I get is the error:
"message": "Trying to get property 'id' of non-object", "status_code": 500,
but if I want to show sum it shows without any problem now here is how I want my API response to look like:
{
id: 1,
sum: 200
},
{
id: 2,
sum: 200
}
Note that sum is the same for all and I just want to repeat it in objects or show them at the end of the API response as a property.
thanks
Hey guys I have a little problem I will try to explain you (is not a technic problem just logic) :
So I have an mongoDB database and I send and receive message (I am doing a message system from user to user) and when I try to see the message and I am doing this for an API.
The problem is that when I do the post method I have to pass as parameter this :
{
"id_transmitter": 2,
"token": "eyJ0...",
"id_receiver": 4
}
Response :
{
"success": "true",
"message": [
[
{
"id": "5b71861fe138231d423a95ef",
"content": "5",
"transmitter": 2,
"Receiver": 4,
"send_at": {
"sec": 1534166559,
"inc": 1
}
}
],
[
{
"id": "5b71861ce138231d423a95ee",
"content": "4",
"transmitter": 2,
"Receiver": 4,
"send_at": {
"sec": 1534166556,
"inc": 1
}
}
],
[
{
"id": "5b718619e138231d423a95ed",
"content": "3",
"transmitter": 2,
"Receiver": 4,
"send_at": {
"sec": 1534166553,
"inc": 1
}
}
],
[
{
"id": "5b718615e138231d423a95ec",
"content": "2",
"transmitter": 2,
"Receiver": 4,
"send_at": {
"sec": 1534166549,
"inc": 1
}
}
]
],
"more": 1
}
As you can see I pass the receiver and the message to see and here is the problem I show only the message that we received OR that we send but not both at same time ... or I have to do 2 repository one with all received and one other with sended and when I will try to show by order of date that will print first one repo and after the other ... and not all together like a converstion should be ...
Here you can find how i did :
/**
*
* #Rest\Post(
* path = "/message/user/list/{page}",
* name = "api_message_list"
* )
*/
public function UserSeeMessageAction(Request $request, $page)
{
$dm = $this->get('doctrine_mongodb');
$messages = $dm->getRepository('AppBundle:MessageUser')->findBy(array
(
'idTransmitter' => ($request->get('id_transmitter')),
'idReceiver' => ($request->get('id_receiver')),
), array('id' => 'DESC'));
//return new JsonResponse([
// 'success' => "true",
// 'message' => $messages,
// 'more' => 0,
//]);
if (($request->get('id_receiver')) == null) {
return new JsonResponse([
'success' => "false",
'message' => "Receveur non renseigné"
]);
}
if (($request->get('id_transmitter')) == null) {
return new JsonResponse([
'success' => "false",
'message' => "Transmetteur non renseigné"
]);
}
if (!isset($messages)) {
return new JsonResponse([
'success' => "false",
'message' => "Pas de messages pour les utilisateurs"
]);
}
$arrayCollection = array();
$entities = 4;
$y = 0;
$x = 0;
foreach($messages as $message) {
if ($y >= ($page * $entities)) {
return new JsonResponse([
'success' => "true",
'message' => $arrayCollection,
'more' => 1,
]);
}
if ($y >= (($page - 1) * $entities) and $y < (($page) * $entities)) {
$x = 1;
$arrayCollection[] = array(
$message,
);
}
$y += 1;
}
if ($x == 1) {
return new JsonResponse([
'success' => "true",
'message' => $arrayCollection,
'more' => 0,
]);
}
return new JsonResponse([
'success' => "false",
'message' => "Plus de message",
]);
}
So for resume : my problem is that I print only sended message or received but not all together
Exemple :
Like it should be :
Hello i am one (send by one)
Hello one ! I am two (send by two)
How are you (send by one)
Fine (send by two)
Like i have :
Hello i am one (send by one)
How are you (send by one)
Hello one ! I am two (send by two)
Fine (send by two)
Like my problem is that i don't know how to set two repo in one .. i want a repo with the messages received and sended
Thx for all that will try to help ! I hope that you understand my bad explanation :)
Nb : The entity :
<?php
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document()
*/
class MessageUser implements \JsonSerializable
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\Field(type="string")
*/
protected $content;
/**
* #MongoDB\Field(type="timestamp")
*/
protected $sendAt;
/**
* #MongoDB\Field(type="boolean")
*/
protected $read;
/**
* #MongoDB\Field(type="integer")
*/
protected $idTransmitter;
/**
* #MongoDB\Field(type="integer")
*/
protected $idReceiver;
/**
* Get id
*
* #return $id
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* #param string $content
* #return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string $content
*/
public function getContent()
{
return $this->content;
}
/**
* Set sendAt
*
* #param $sendAt
* #return $this
*/
public function setSendAt($sendAt)
{
$this->sendAt = $sendAt;
return $this;
}
/**
* Get sendAt
*
* #return $sendAt
*/
public function getSendAt()
{
return $this->sendAt;
}
/**
* Set read
*
* #param boolean $read
* #return $this
*/
public function setRead($read)
{
$this->read = $read;
return $this;
}
/**
* Get read
*
* #return boolean $read
*/
public function getRead()
{
return $this->read;
}
/**
* Set idTransmitter
*
* #param integer $idTransmitter
* #return $this
*/
public function setIdTransmitter($idTransmitter)
{
$this->idTransmitter = $idTransmitter;
return $this;
}
/**
* Get idTransmitter
*
* #return integer $idTransmitter
*/
public function getIdTransmitter()
{
return $this->idTransmitter;
}
/**
* Set idReceiver
*
* #param integer $idReceiver
* #return $this
*/
public function setIdReceiver($idReceiver)
{
$this->idReceiver = $idReceiver;
return $this;
}
/**
* Get idReceiver
*
* #return integer $idReceiver
*/
public function getIdReceiver()
{
return $this->idReceiver;
}
function jsonSerialize()
{
return array(
"id" => $this->id,
"content" => $this->content,
"transmitter" => $this->idTransmitter,
"Receiver" => $this->idReceiver,
"send_at" => $this->sendAt,
);
}
}
I have a very specific case in Laravel framework pagination.
Imagine I get my results from a Redis API by passing offset and limit parameters. In the other words, the paginating stuff is done on the API side.
Now when I get the results in my Laravel app I want to show them in a pagination. I mean a simple pagination view that offers a navigation to the other pages. for example, the second page means I have to send a request to my Redis API in order to get the second set of data.
Based on what I understand From Laravel paginator class, it needs a collection of items and gives a convenient pagination over them. Something that is a bit different from what I want.
I need a Class only for making the pagination view which gets a total number of items as a parameter and makes the appropriate links layout.
Is there a convenient way to do this in Laravel?
or
is implementing it by myself my only option?
I'm using below class to get data in pagination using data:-
namespace App\Helpers;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;
use Countable;
use ArrayAccess;
use ArrayIterator;
use JsonSerializable;
use IteratorAggregate;
use Illuminate\Pagination\LengthAwarePaginator;
class LengthAwareOffsetPaginator extends LengthAwarePaginator implements
Arrayable,
ArrayAccess,
Countable,
IteratorAggregate,
JsonSerializable,
Jsonable
{
protected $items;
protected $total;
protected $total_pages;
protected $limit;
protected $offset;
protected $options;
/**
* LengthAwareOffsetPaginator constructor.
*
* #param Collection $items
* #param $total
* #param $limit
* #param $offset
* #param array $options
*/
public function __construct(Collection $items, $total, $limit, $offset, array $options = [])
{
$this->items = $items;
if ($items->count() > $limit) {
$this->items = $items->take($limit);
}
$this->total = $total;
$this->limit = $limit;
$this->offset = $offset;
$this->options = $options;
$this->total_pages = ($total/$limit);
}
/**
* Get url of an offset.
*
* #param int $offset
*
* #return string Url of an offset
*/
public function url($pageNumber)
{
$query = isset($this->options['queryParameter']) ? $this->options['queryParameter'] : [];
$offset = ($pageNumber - 1) * $this->limit;
$query = array_merge($query, ['page' => ['limit' => $this->limit, 'offset' => $offset]]);
$url = isset($this->options['path']) ? $this->options['path'] : '/';
return $url.'?'.http_build_query($query);
}
/**
* Get last page.
*
* #return int Last page
*/
public function lastPage()
{
$totalPages = ceil($this->total / $this->limit);
return $totalPages;
}
/**
* Get last page offset.
*
* #return int Last page offset
*/
public function totalPages()
{
return $this->total_pages;
}
/**
* Get current page.
*
* #return int Last page offset
*/
public function currentPage()
{
$pages = (int)ceil($this->offset / $this->limit);
$currentPage = ($pages + 1);
return $currentPage;
}
public function perPage()
{
return $this->limit;
}
/**
* Get last page url.
*
* #return string
*/
public function lastPageUrl()
{
$last = $this->lastPage();
return $this->url($last);
}
/**
* get next page url.
*
* #return string
*/
public function nextPageUrl()
{
$nextOffset = $this->offset + $this->limit;
return ($nextOffset >= $this->total)
? null
: $this->url($nextOffset);
}
/**
* get previous page url.
*
* #return string
*/
public function previousPageUrl()
{
if ($this->offset == 0) {
return null;
}
$prevOffset = $this->offset - $this->limit;
return ($prevOffset < 0)
? $this->url($prevOffset + $this->limit - $this->offset)
: $this->url($prevOffset);
}
public function items()
{
return $this->items;
}
/**
* get total items.
*
* #return int
*/
public function total()
{
return $this->total;
}
/**
* Get the number of items for the current page.
*
* #return int
*/
public function count()
{
// return $this->total;
return $this->items->count();
}
/**
* Get an iterator for the items.
*
* #return \ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->items->all());
}
/**
* Determine if the given item exists.
*
* #param mixed $key
*
* #return bool
*/
public function offsetExists($key)
{
return $this->items->has($key);
}
/**
* Get the item at the given offset.
*
* #param mixed $key
*
* #return mixed
*/
public function offsetGet($key)
{
return $this->items->get($key);
}
/**
* Set the item at the given offset.
*
* #param mixed $key
* #param mixed $value
*/
public function offsetSet($key, $value)
{
$this->items->put($key, $value);
}
/**
* Unset the item at the given key.
*
* #param mixed $key
*/
public function offsetUnset($key)
{
$this->items->forget($key);
}
/**
* Get the instance as an array.
*
* #return array
*/
public function toArray()
{
return [
'first' => $this->url(0),
'last' => $this->lastPageUrl(),
'next' => $this->nextPageUrl(),
'prev' => $this->previousPageUrl(),
'data' => $this->items->toArray(),
];
}
/**
* Convert the object into something JSON serializable.
*
* #return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
/**
* Convert the object to its JSON representation.
*
* #param int $options
*
* #return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
}
you need to call this like:
$options['queryParameter'] = [
'page' => [
'limit' => 10,
'offset' => 0
],
'path' => \Illuminate\Pagination\Paginator::resolveCurrentPath()
];
$result = new LengthAwareOffsetPaginator(
collect($data),
$totalItemsCount,
$this->limit,
$this->offset,
$options
);
This will give you following output:
{
"data": [
{
....
},
{
....
}
],
"meta": {
"pagination": {
"total": 110,
"count": 10,
"per_page": 10,
"current_page": 1,
"total_pages": 11,
"links": [
"self": "url/pages?page=1",
"next": "url/pages?page=2",
"first": "url/pages?page=1",
"last": "url/pages?page=11"
]
}
}
}
I think this will help you.
I'm working on a Laravel 5.4 project and I've downloaded the crud generator package, but when I use the --datatables=true tag and I go to the view I'm getting the error:
FatalThrowableError in ProiodaController.php line 32:
Call to undefined method App\DataTables\ProiodaDataTable::render()
I am using the yajra/laravel-datatables such the generator to works need it.
The Generator has generate all the view files controller request model repositories and in a folder called DataTables has generate a file named ProiodaDataTable.php.
Below is The ProiodaController.php
<?php
namespace App\Http\Controllers;
use App\DataTables\ProiodaDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateProiodaRequest;
use App\Http\Requests\UpdateProiodaRequest;
use App\Repositories\ProiodaRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class ProiodaController extends AppBaseController
{
/** #var ProiodaRepository */
private $proiodaRepository;
public function __construct(ProiodaRepository $proiodaRepo)
{
$this->proiodaRepository = $proiodaRepo;
}
/**
* Display a listing of the Proioda.
*
* #param ProiodaDataTable $proiodaDataTable
* #return Response
*/
public function index(ProiodaDataTable $proiodaDataTable)
{
return $proiodaDataTable->render('proiodas.index');
}
/**
* Show the form for creating a new Proioda.
*
* #return Response
*/
public function create()
{
return view('proiodas.create');
}
/**
* Store a newly created Proioda in storage.
*
* #param CreateProiodaRequest $request
*
* #return Response
*/
public function store(CreateProiodaRequest $request)
{
$input = $request->all();
$proioda = $this->proiodaRepository->create($input);
Flash::success('Proioda saved successfully.');
return redirect(route('proiodas.index'));
}
/**
* Display the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.show')->with('proioda', $proioda);
}
/**
* Show the form for editing the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.edit')->with('proioda', $proioda);
}
/**
* Update the specified Proioda in storage.
*
* #param int $id
* #param UpdateProiodaRequest $request
*
* #return Response
*/
public function update($id, UpdateProiodaRequest $request)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$proioda = $this->proiodaRepository->update($request->all(), $id);
Flash::success('Proioda updated successfully.');
return redirect(route('proiodas.index'));
}
/**
* Remove the specified Proioda from storage.
*
* #param int $id
*
* #return Response
*/
public function destroy($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$this->proiodaRepository->delete($id);
Flash::success('Proioda deleted successfully.');
return redirect(route('proiodas.index'));
}
}
Here is The ProiodaDataTable.php
<?php
namespace App\DataTables;
use App\Models\Proioda;
use Form;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\View;
class ProiodaDataTable extends Datatables
{
/*
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', 'proiodas.datatables_actions')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* #return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$proiodas = Proioda::query();
return $this->applyScopes($proiodas);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'scrollX' => false,
'buttons' => [
'print',
'reset',
'reload',
[
'extend' => 'collection',
'text' => '<i class="fa fa-download"></i> Export',
'buttons' => [
'csv',
'excel',
'pdf',
],
],
'colvis'
]
]);
}
/**
* Get columns.
*
* #return array
*/
private function getColumns()
{
return [
'onoma' => ['name' => 'onoma', 'data' => 'onoma'],
'perigrafi' => ['name' => 'perigrafi', 'data' => 'perigrafi'],
'timi' => ['name' => 'timi', 'data' => 'timi']
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'proiodas';
}
}
Hi i am getting an error with laravel 5.4 i am using infyom/laravel-generator package and when i use the php artisan infyom:scaffold ModelName --datatables=true when i go to the view im getting the error.
FatalThrowableError in ProiodaController.php line 32: Call to undefined method App\DataTables\ProiodaDataTable::render()
This is my controller ProiodaController.php
<?php
namespace App\Http\Controllers;
use App\DataTables\ProiodaDataTable;
use App\Http\Requests;
use App\Http\Requests\CreateProiodaRequest;
use App\Http\Requests\UpdateProiodaRequest;
use App\Repositories\ProiodaRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
class ProiodaController extends AppBaseController
{
/** #var ProiodaRepository */
private $proiodaRepository;
public function __construct(ProiodaRepository $proiodaRepo)
{
$this->proiodaRepository = $proiodaRepo;
}
/**
* Display a listing of the Proioda.
*
* #param ProiodaDataTable $proiodaDataTable
* #return Response
*/
public function index(ProiodaDataTable $proiodaDataTable)
{
return $proiodaDataTable->render('proiodas.index');
}
/**
* Show the form for creating a new Proioda.
*
* #return Response
*/
public function create()
{
return view('proiodas.create');
}
/**
* Store a newly created Proioda in storage.
*
* #param CreateProiodaRequest $request
*
* #return Response
*/
public function store(CreateProiodaRequest $request)
{
$input = $request->all();
$proioda = $this->proiodaRepository->create($input);
Flash::success('Proioda saved successfully.');
return redirect(route('proiodas.index'));
}
/**
* Display the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function show($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.show')->with('proioda', $proioda);
}
/**
* Show the form for editing the specified Proioda.
*
* #param int $id
*
* #return Response
*/
public function edit($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
return view('proiodas.edit')->with('proioda', $proioda);
}
/**
* Update the specified Proioda in storage.
*
* #param int $id
* #param UpdateProiodaRequest $request
*
* #return Response
*/
public function update($id, UpdateProiodaRequest $request)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$proioda = $this->proiodaRepository->update($request->all(), $id);
Flash::success('Proioda updated successfully.');
return redirect(route('proiodas.index'));
}
/**
* Remove the specified Proioda from storage.
*
* #param int $id
*
* #return Response
*/
public function destroy($id)
{
$proioda = $this->proiodaRepository->findWithoutFail($id);
if (empty($proioda)) {
Flash::error('Proioda not found');
return redirect(route('proiodas.index'));
}
$this->proiodaRepository->delete($id);
Flash::success('Proioda deleted successfully.');
return redirect(route('proiodas.index'));
}
}
This is ProiodaDataTable.php
<?php
namespace App\DataTables;
use App\Models\Proioda;
use Form;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\View;
class ProiodaDataTable extends Datatables
{
/**
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', 'proiodas.datatables_actions')
->make(true);
}
/**
* Get the query object to be processed by datatables.
*
* #return \Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder
*/
public function query()
{
$proiodas = Proioda::query();
return $this->applyScopes($proiodas);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\Datatables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'scrollX' => false,
'buttons' => [
'print',
'reset',
'reload',
[
'extend' => 'collection',
'text' => '<i class="fa fa-download"></i> Export',
'buttons' => [
'csv',
'excel',
'pdf',
],
],
'colvis'
]
]);
}
/**
* Get columns.
*
* #return array
*/
private function getColumns()
{
return [
'onoma' => ['name' => 'onoma', 'data' => 'onoma'],
'perigrafi' => ['name' => 'perigrafi', 'data' => 'perigrafi'],
'timi' => ['name' => 'timi', 'data' => 'timi']
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'proiodas';
}
}
Can someone help me please!!