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);
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**
i have a problem when i use API Resources inside another API Resources class like this:
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
but when I remove the class the problem disappears like this :
if (! Route::is('job.*')) {
$data['sites']= $this->sites;
$data['jobs'] = $this->jobs;
}
this is -> image for error
this is my code :
class CustomerResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'billing_details' => $this->billing_details,
'billing_info' => [
'address' => $this->billing->address,
'street_num' =>$this->billing->street_num,
'country' =>$this->billing->country->name,
'city' =>$this->billing->city,
'postal_code' =>$this->billing->postal_code,
'credit_limit' =>$this->billing->credit_limit,
'payment_term_id' =>$this->billing->payment_term_id,
'send_statement' =>$this->billing->send_statement
],
'contacts' => $this->contacts,
'sitecontact' => $this->sitecontact,
];
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
return $data;
}
}
I called CustomerRessource class on JobRessource class which leads to an infinite loop between them
JobRessource class
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
I fixed it by using this condition on JobRessource
if (Route::is('job.*')) {
$data['customer' ] = new CustomerResource($this->customer);
}
JobRessource with condition
#N69S thank you for your comment
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
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.