I'm using Dingo API to create an API in Laravel 5.2 and have a controller returning data with
return $this->response->paginator($rows, new SymptomTransformer, ['user_id' => $user_id]);
However, I don't know how to retrieve user_id value in the SymptomTransformer! Tried many different ways and tried looking into the class but I'm relatively new to both Laravel and OOP so if anyone can point me to the right direction, it'd be greatly appreciated.
Below is my transformer class.
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
You can pass extra parameter to transformer constructor.
class SymptomTransformer extends TransformerAbstract
{
protected $extra;
public function __construct($extra) {
$this->extra = $exta;
}
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->extra);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}
And call like
return $this->response->paginator($rows, new SymptomTransformer(['user_id' => $user_id]));
You can set extra param via setter.
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->test_param);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
public function setTestParam($test_param)
{
$this->test_param = $test_param;
}
}
And then:
$symptomTransformer = new SymptomTransformer;
$symptomTransformer->setTestParam('something');
return $this->response->paginator($rows, $symptomTransformer);
If you are using Dependency Injection, then you need to pass params afterwards.
This is my strategy:
<?php
namespace App\Traits;
trait TransformerParams {
private $params;
public function addParam() {
$args = func_get_args();
if(is_array($args[0]))
{
$this->params = $args[0];
} else {
$this->params[$args[0]] = $args[1];
}
}
}
Then you implement the trait in your transformer:
<?php
namespace App\Transformers;
use App\Traits\TransformerParams;
use App\User;
use League\Fractal\TransformerAbstract;
class UserTransformer extends TransformerAbstract
{
use TransformerParams;
public function transform(User $user)
{
return array_merge([
'id' => (int) $user->id,
'username' => $user->username,
'email' => $user->email,
'role' => $user->roles[0],
'image' => $user->image
], $this->params); // in real world, you'd not be using array_merge
}
}
So, in your Controller, just do this:
public function index(Request $request, UserTransformer $transformer)
{
$transformer->addParam('has_extra_param', ':D');
// ... rest of the code
}
Basically, the trait is a bag for extra params.
Related
The Files I'm Using :
<?php
namespace App\GraphQl\Query\User;
use App\GraphQl\Traits\UserTrait;
use App\Models\User;
use GraphQL\Type\Definition\ResolveInfo;
use Rebing\GraphQL\Support\Facades\GraphQL;
use GraphQL\Type\Definition\Type;
use Rebing\GraphQL\Support\Query;
The GraphQl UserRolesQuery File :
use Closure;
class UserRolesQuery extends Query
{
use UserTrait;
protected $attributes = [
'name' => 'user',
];
public function type(): Type
{
return GraphQL::type('UserType');
}
public function args(): array
{
return [
'id' => [
'name' => 'id',
'type' => Type::int(),
// 'rules' => ['required'] validation
],
];
}
public function resolve($root, array $args, $context, ResolveInfo $resolveInfo, Closure $getSelectFields)
{
The Resolve Function Where I Expect To Return User Role Names
$user = User::find($args['id']);
$result = $user->getRoleNames();
return $result;
}
}
I Expect The** $user->getRoleNames(); To Return The User Roles Name .. But it always returns NULL**
Adding content from Laravel to Firebase database as follows:
$postRef = $this->database->getReference($this->tablename)->push($postData);
But I don't know how to add content from Laravel to Firestore. This is my Firestore:
This is how Laravel looks like:
These are my codes:
<?php
namespace App\Http\Controllers\Firebase;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Kreait\Firebase\Contract\Firestore;
class ContactController extends Controller
{
public function __construct(Firestore $firestore)
{
$this->firestore = $firestore;
$this->tablename = 'kategoriler';
}
public function index()
{
return view('firebase.contact.index');
}
public function create()
{
return view('firebase.contact.create');
}
public function store(Request $request)
{
$postData = [
'comment' => $request->comment,
'iD' => $request->iD,
'imgUrl' => $request->imgUrl,
'lat' => $request->lat,
'location' => $request->location,
'lon' => $request->lon,
'name' => $request->name,
'youtubeId' => $request->youtubeId,
];
$postRef = $this->app('firebase.firestore')->database()->collection($this->tablename)->Document(0)->collection('bolgeler')->push($postData);
if($postRef)
{
return redirect('contacts')->with('durum','İçerik eklendi.');
}
else
{
return redirect('contacts')->with('durum','İçerik eklenemedi.');
}
If you want add data to bolgeler collection with auto document name, you can do this :
$postRef = $this->app('firebase.firestore')->database()->collection('bolgeler')->newDocument()->set($postData);
or :
$posref = $this->firestore->database()->collection('bolgeler')->newDocument()->set($postData);
when you nedd add specific name :
$postRef = $this->app('firebase.firestore')->database()->collection('bolgeler')->document('id001')->set($postData);
or:
$posref = $this->firestore->database()->collection('bolgeler')->document('id001)->set($postData);
I have an end API point
users/{user}
now in User resource, I want to return
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
// 'comments' => $this->post->comments->keyBy('post_id')
'comments' => new CommentCollection($this->post->comments->keyBy->post_id)
];
}
CommentCollection class
public function toArray($request)
{
// return parent::toArray($request);
return [
'data' => $this->collection->transform(function($comment){
return [
'id' => $comment->id,
'comment' => $comment->comment,
];
}),
];
}
but the result will not include the post_id as key, how I can make it return the comments collection having key post_id?
Update
use App\models\Post;
use App\Http\Resources\Postas PostResource;
Route::get('/posts', function () {
return PostResource::collection(Post::all()->keyBy->slug);
});
This is working correctly, but if I will use post collection inside User resource as relationship, it is not working! and that is my requirement in comments collection.
What I did it, I created another ResourceGroupCollection class
<?php
namespace App\Http\Resources\Collection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentGroupCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\Collection\CommentCollection';
public $preserveKeys = true;
public function toArray($request)
{
return $this->collection;
}
}
<?php
namespace App\Http\Resources\Collection;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CommentCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\Comment';
public $preserveKeys = true;
public function toArray($request)
{
return $this->collection;
}
}
and then
new CommentGroupCollection($comments->groupBy('post_id')),
just like this :
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
// 'comments' => $this->post->comments->keyBy('post_id')
'comments' => new CommentCollection($this->post->comments)->keyBy('post_id')
];
}
I'm supposed to display author details in bookformat method. But facing LogicException. Any suggestions thanks in advance. Im getting error like this LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation. Any help that would be great for me. If I comment authors in bookFormat() everything works fine. But Idk why I'm unable to get author details in my bookformat().
#booksController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Models\Book;
use App\Models\Author;
class BooksController extends Controller
{
public function index()
{
$books = Book::all();
$results = [];
foreach ($books as $book) {
$results [] = $this->bookFormat($book);
}
return $results;
}
public function bookFormat($book){
return [
'Id' => $book->id,
'Title' => $book->title,
'Author' => [
'Id' => $book->author->id,
'First_name' => $book->author->first_name,
'Last_name' => $book->author->last_name
],
'Price' => $book->price,
'ISBN' => $book->isbn,
'Language' => $book->language,
'Year' => $book->year_of_publisher
];
}
}
//book.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
public $timestamps = TRUE;
protected $table = 'books';
//rules
public static $rules = [
'title' => 'required|max:255',
'isbn' => 'required|max:50',
'author_id' => 'required|max:255',
'language' => 'required|max:255',
'price' => 'required|max:255',
'year_of_publisher' => 'required'
];
//relationship
public function author() {
$this->belongsTo(Author::class);
}
}
Instead of:
public function author() {
$this->belongsTo(Author::class);
}
you should have:
public function author() {
return $this->belongsTo(Author::class);
}
Notice the return difference.
I'm trying to set validation on my controller method, but on validation failure I'm getting error that method is not allowed http exception.
My controller:
namespace App\Http\Controllers\Web;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Services\InvoicesService;
class InvoiceController extends Controller
{
private $invoice;
public function __construct(InvoicesService $invoice) {
$this->invoice = $invoice;
}
public function startNewInvoice($id, $customer)
{
$ticket = $this->invoice->getTicketByInvoice($id);
$ticket = $ticket->Ticket;
return view('form', ['InvoiceId' => $id,'CustomerInfo' => $customer, 'records' => null, 'recordState' => null, 'ticket' => $ticket, 'invoices' => null]);
}
public function generateInvoice(Request $request)
{
//dd($request);
$this->validate($request, [
'CustomerNumber' => 'required|numeric'
]);
$invoiceId = $request->input('Invoice');
$customer = array('CustomerCode' => $request->input('CustomerNumber'),'CustomerName' => $request->input('CustomerName'),'CustomerAddress' => $request->input('CustomerAddress'),
'CustomerVATCode' => $request->input('CustomerVatNumber'));
$hash = $this->invoice->generateInvoice($invoiceId, $customer);
$newInvoice = $this->invoice->newInvoice($request->input('CustomerNumber'), $hash->Id);
return $this->startNewInvoice($newInvoice->Id, $customer);
}
}
Any help would be really appreciated