I am using fractal for my small project, here is my code:
public function transform(Series $series) {
return [
'id' => $series->id,
'title' => $series->title,
'url' => $series->url,
'description' => $series->description,
'thumbnail_hd' => $series->thumbnail_hd,
'thumbnail_wide' => $series->thumbnail_wide,
'views' => $series->views
];
}
I would like to make views (which is an int) optional and not return the views unless requested - since this field is based on a relationship and will increase the processing time.
I would like to use it as relationships (so i can include particular fields whenever I need to):
// in transformer
public function includeUser(Series $series) {
return $this->item($series->user, new UserTransformer);
}
// in controller
return fractal()
->item($series)
->parseIncludes(['user'])
->transformWith(new SeriesTransformer)
->toArray();
But just for an integer instead of a whole array of data. Is it possible using Fractal?
What you can do is the following
public function transform(Series $series) {
$return = [
'id' => $series->id,
'title' => $series->title,
'url' => $series->url,
'description' => $series->description,
'thumbnail_hd' => $series->thumbnail_hd,
'thumbnail_wide' => $series->thumbnail_wide,
];
if ($series->views > 0) {
$return['views'] = (int) $series->views;
}
return $return;
}
I wouldn't suggest doing this though. I would usually just return views as 0.
If you're worried about your DB performance, your app is going to have to count the views anyway to know if they're greater than 0.
If you worried about client side performance, this is not going to matter with a single key value pair.
Related
I am trying to add an asset link to a nested properties value using Eloquents API resource function:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'image' => isset($this->image) ? asset('storage/'.$this->image) : null,
'properties' => $this->properties,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at
];
}
The following works fine for the image value, but I am using a nested properties['pdf'] file that I need to add asset('storage/') parameter to so it outputs the full URL.
How am I able to pass isset($this->properties['pdf']) ? asset('storage/'.$this->properties['pdf']) : null into the properties value? I still need the pdf value to return inside the properties value.
Note: There are other values inside properties but they are dynamic based on the data returned.
Probably not the cleanest idea but this worked:
$properties = $this->properties;
if(isset($this->properties['pdf']) && $this->properties['pdf'] != null){
$properties['pdf'] = asset('storage/'.$this->properties['pdf']);
}
Then I applied $properties to the return.
I'm learning Laravel and have created a public endpoint where I want to output only certain information of some comments if a user is not authenticated from a GET request.
I have managed to filter out the comments based on whether or not they are approved. I now want to filter out the data that is returned. I have attached a screenshot of what is currently returned.
Ideally, I only want to return the id, name and the body in the json. How can I go about this? I tried the pluck() method which did not give the desired results. Any pointers would be greatly appreciated
public function index(Request $request)
{
if (Auth::guard('api')->check()) {
return Comment::all();
} else {
$comments = Comment::where('approved', 1)->get();
return $comments->pluck('id','name','body');
}
}
To select the particular columns, you can pass columns name to get as
$comments = Comment::where('approved', 1) -> get(['id','name','body']);
You can use a transformer to map the incoming data to a sensible output based on the auth state. The following example comes from the Fractal lib:
<?php
use Acme\Model\Book;
use League\Fractal;
$books = Book::all();
$resource = new Fractal\Resource\Collection($books, function(Book $book) {
return [
'id' => (int) $book->id,
'title' => $book->title,
'year' => $book->yr,
'author' => [
'name' => $book->author_name,
'email' => $book->author_email,
],
'links' => [
[
'rel' => 'self',
'uri' => '/books/'.$book->id,
]
]
];
});
Ideally, you would create 2 classes that extend from Transformer and pass the correct one to the output.
If you want to pass the result as json respose
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return Response::json($comments);
If you want to pass the result as to blade
$comments = Comment::where('approved', 1)->pluck('id','name','body')->toArray();
return view('your_blade_name')->with('comments',$comments);
I have difficult to build and return a nested json. I want obtain the information from two differents table joined with an id.
This is my situation:
With this method on my controller:
public function eventOccList(EventOccurrence $eventOccurrence){
return new EventOccurrenceResourceCollection(EventOccurrence::all());
}
and with the mapping in the class EventOccurrenceResource
return [
'type' => 'event',
'id' => (string) $this->id,
'name' => $this->name,
'description' => $this->description,
'location_id' => $this->location_id
];
I obtain this JSON:
{"data":[{"type":"event","id":"1","name":"event_1","description":"event blabla","location_id":11}
If I want to obtain all the informations about the table "location" with the id "location_id" and show in the same json, what is the best way to retrieved this data?
Thanks !
I assume your Event Model have a location relationship :
public function location{
return $this->belongsTo(Event::class);
}
you can do this once you have your event in a Controller :
$event->load('location');
return $event->toJson();
You can then hide or append any attribute you want :)
I am using faker to seed my DB.
$factory->define(App\Product::class, function (Faker\Generator $faker) {
$campaign = factory(App\Campaign::class)->create();
$size= $faker->randomElement($array = array ('728x90','300x250','315x315', '715x425', '750x650'));
return [
'campaign_id' => $campaign->campaign_name,
'size' => $size,
'product_id' => $campaign->campaign_name."_".$size,
'version' => $faker->randomElement($array = array ('1','2','3', '4', '5')),
];
});
The bit I am interested in is the version field. What I would like to do is generate a random number between 1 and 5 and then enter that number of records in the database,
So a product can have been 1 and 5 entries depending on the number of 'versions' which have bene created.
Is this possible?
I tried a simple for loop around the return array with no luck.
From what you say, you want to create multiple entries for the same product with different versions. The Model factory can be used to create a single model entry. You can use the faker directly in the seeder and achieve what you are expecting.
$campaign = factory(App\Campaign::class)->create();
$size= $faker->randomElement($array = array ('728x90','300x250','315x315', '715x425', '750x650'))
$max_version = $faker->randomElement($array = array ('1','2','3', '4', '5'));
for ($version=0; $version < $max_version; $version++) {
Product::create([
'campaign_id' => $campaign->campaign_name,
'size' => $size,
'product_id' => $campaign->campaign_name."_".$size,
'version' => $version,
]);
}
One of the simplest solutions is to create factory method (or trait) in your test class, something like this, you'll get the point :)
public function createProduct()
{
$product = factory(Product::class)->create();
foreach(range(0, $product->version) as $i) {
factory(Version::class)->create([
'product_id' => $product->id
]);
}
return $product;
}
I am using Doctrine 2 in my Zend Framework 2 Project. I have now created a Form and create one of my Dropdowns with Values from the Database. My Problem now is that I want to change which values are used and not the one which I get back from my repository. Okay, here some Code for a better understanding:
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'county',
'options' => array(
'object_manager' => $this->getObjectManager(),
'label' => 'County',
'target_class' => 'Advert\Entity\Geolocation',
'property' => 'county',
'is_method' => true,
'empty_option' => '--- select county ---',
'value_options'=> function($targetEntity) {
$values = array($targetEntity->getCounty() => $targetEntity->getCounty());
return $values;
},
'find_method' => array(
'name' => 'getCounties',
),
),
'allow_empty' => true,
'required' => false,
'attributes' => array(
'id' => 'county',
'multiple' => false,
)
)
);
I want to set the value for my Select to be the County Name and not the ID. I thought that I would need the 'value_options' which needs an array. I tried it like above, but get the
Error Message: Argument 1 passed to Zend\Form\Element\Select::setValueOptions() must be of the type array, object given
Is this possible at all?
I was going to suggest modifying your code, although after checking the ObjectSelect code i'm surprised that (as far as I can tell) this isn't actually possible without extending the class. This is because the value is always generated from the id.
I create all form elements using factories (without the ObjectSelect), especially complex ones that require varied lists.
Alternative solution
First create a new method in the Repository that returns the correct array. This will allow you to reuse that same method should you need it anywhere else (not just for forms!).
class FooRepository extends Repository
{
public function getCounties()
{
// normal method unchanged, returns a collection
// of counties
}
public function getCountiesAsArrayKeyedByCountyName()
{
$counties = array();
foreach($this->getCounties() as $county) {
$counties[$county->getName()] = $county->getName();
}
return $counties;
}
}
Next create a custom select factory that will set the value options for you.
namespace MyModule\Form\Element;
use Zend\Form\Element\Select;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
class CountiesByNameSelectFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $formElementManager)
{
$element = new Select;
$element->setValueOptions($this->loadValueOptions($formElementManager));
// set other select options etc
$element->setName('foo')
->setOptions(array('foo' => 'bar'));
return $element;
}
protected function loadValueOptions(ServiceLocatorInterface $formElementManager)
{
$serviceManager = $formElementManager->getServiceLocator();
$repository = $serviceManager->get('DoctrineObjectManager')->getRepository('Foo/Entity/Bar');
return $repository->getCountiesAsArrayKeyedByCountyName();
}
}
Register the new element with the service manager by adding a new entry in Module.php or module.config.php.
// Module.php
public function getFormElementConfig()
{
return array(
'factories' => array(
'MyModule\Form\Element\CountiesByNameSelect'
=> 'MyModule\Form\Element\CountiesByNameSelectFactory',
),
);
}
Lastly change the form and remove your current select element and add the new one (use the name that you registered with the service manager as the type key)
$this->add(array(
'name' => 'counties',
'type' => 'MyModule\Form\Element\CountiesByNameSelect',
));
It might seem like a lot more code (because it is) however you will benefit from it being a much clearer separation of concerns and you can now reuse the element on multiple forms and only need to configure it in one place.