I have a problem on API Resources Laravel (Maximum stack depth exceeded) - php

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

Related

How to add content from Laravel to Firestore?

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);

localhost send an invalid response code igniter 4

I'm just learning CI4 from Youtube "web programming unpas" on episode 9 insert data (its using indonesia language). Well I followed the course and tried to insert data. After insert data to database, it will be redirected to the index file.
So the error is showing localhost send an invalid response
Idk what's the problem
Here is the code
routes.php
$routes->get('/', 'pages::index');
$routes->get('/komik/create', 'komik::create');
$routes->get('/komik/(:segment)', 'komik::detail/$1');
controller/komik.php
<?php
namespace App\Controllers;
use App\Models\komikmodel;
class komik extends BaseController
{
protected $komikmodel;
public function __construct()
{
$this->komikmodel = new komikmodel();
}
public function index()
{
$data = [
'title' => 'Daftar Komik' ,
'komik' => $this->komikmodel->getkomik()
];
return view('komik/index', $data);
}
public function detail($slug)
{
$data = [
'title' => 'Detail Komik',
'komik' => $this->komikmodel->getkomik($slug)
];
if(empty($data['komik']))
{
throw new \CodeIgniter\Exceptions\PageNotFoundException('Judul Komik '. $slug. 'Tidak Ditemukan');
}
return view('komik/detail', $data);
}
public function create()
{
$data = [
'title' => 'Form Tambah Data Komik'
];
return view('/komik/create', $data);
}
public function save()
{
$slug = url_title($this->request->getVar('judul'), '-', true);
$this->komikmodel->save([
'judul' => $this->request->getVar('judul'),
'slug' => $slug,
'penulis' => $this->request->getVar('penulis'),
'penerbit' => $this->request->getVar('penerbit'),
'sampul' => $this->request->getVar('sampul')
]);
session()->setFlashData('pesan', 'Data berhasil di tambahkan!');
return redirect()->to('/komik');
}
}
Any advice will be appreciated

Remove empty array in Resource::Collection not working Laravel

I want to remove empty array when its return. I have been trying in many different ways, help plz
My controller looks :
public function index()
{
return JobsResource::collection(Jobs::all())->filter();
}
my resource file look:
class JobsCollection extends Resource
{
public function toArray($request)
{
$applicants_count =Job_applicants::where('job_id',$this->id)->get()->count();
if ($applicants_count>0) {
return [
'id' => $this->id,
'title' => $this->title,
'deadline' => $this->deadline,
'applicants_count' => $applicants_count,
'applicants' => new EmployeesResource($this->Employeess->take(2))
];
}
}
}
it always return an empty array
output :
[
[],
{
"id":99,
"title":"Construction Administrator - The Woodlands",
"deadline":"2018-06-30",
"applicants_count":10,
"applicants":[
{
"name":"Mr. Job Seeker",
"pivot":{
"job_id":99,
"employee_id":1
}
},
{
"name":"Michale Feil",
"pivot":{
"job_id":99,
"employee_id":2
}
}
]
}
Controller:
public function index() {
$jobs = Jobs::has('Employeess')->with('Employeess')->withCount('Employeess')->get();
return JobsResource::collection($jobs);
}
Resource file:
class JobsCollection extends Resource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'deadline' => $this->deadline,
'applicants_count' => $this->Employeess_count,
'applicants' => new EmployeesResource($this->Employeess->take(2))
];
}
}

LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

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.

Laravel Fractal transformer, how to pass and get extra variable

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.

Categories