I'm trying to create a route in the api.php file in laravel 6, I'm returning a simple array just for testing, but it always gives an error, in the web.php routes file it works normally, but in the api.php file it doesn't work
Object { message: "", exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException", file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php", line: 179, trace: (21) […] }
exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php"
line: 179
message: ""
trace: Array(21) [ {…}, {…}, {…}, … ]
0: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 635, function: "match", … }
1: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 624, function: "findRoute", … }
2: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Routing/Router.php", line: 613, function: "dispatchToRoute", … }
3: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 170, function: "dispatch", … }
4: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 130, function: "Illuminate\\Foundation\\Http\\{closure}", … }
5: Object { file: "/var/www/app/Http/Middleware/Cors.php", line: 18, function: "Illuminate\\Pipeline\\{closure}", … }
6: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
7: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
8: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
9: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php", line: 21, function: "Illuminate\\Pipeline\\{closure}", … }
10: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
11: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php", line: 27, function: "Illuminate\\Pipeline\\{closure}", … }
12: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
13: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php", line: 63, function: "Illuminate\\Pipeline\\{closure}", … }
14: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
15: Object { file: "/var/www/vendor/fideloper/proxy/src/TrustProxies.php", line: 57, function: "Illuminate\\Pipeline\\{closure}", … }
16: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 171, function: "handle", … }
17: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php", line: 105, function: "Illuminate\\Pipeline\\{closure}", … }
18: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 145, function: "then", … }
19: Object { file: "/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php", line: 110, function: "sendRequestThroughRouter", … }
20: Object
Code Route:
Route::get('/api-teste',
['uses' => 'RegisterController#show']
);
Code Controller:
public function show()
{
return response()->json([
'nome' => 'paulo',
'genero' => 'masculino',
]);
}
I already tried with route resource and also, clear the cache
sudo docker exec -it phpgold-app php artisan optimize'
OBS: I'm using docker container, but it works perfectly in the web.php file
Related
In a Symfony project, I have a user-contacts.json file which contains :
[
{
"id": 137,
"userName": "testUserName",
"userEmail": "test#email.com",
"userQuestion": "This is my question ?",
"solved": false
}
]
In a service, I'm receiving an object coming from a symfony form, here is the content:
ContactFile.php on line 18:
App\Entity\Contact {#561 ▼
-id: 146
-userName: "Contact"
-userEmail: "test#test.com"
-userQuestion: "test ?"
-solved: false
}
I'd like to append this contact query to the user-contacts.json file, in a way that the user-contacts.json content has a valid JSON format, like so for example:
[
{
"id": 137,
"userName": "testUserName",
"userEmail": "test#email.com",
"userQuestion": "This is my question ?",
"solved": false
},
{
"id": 138,
"userName": "anotherUserName",
"userEmail": "another#email.com",
"userQuestion": "This is another question ?",
"solved": false
}
]
Unfortunately, here is my result right now:
[
[
{
"id": 148,
"userName": "anotherUserName",
"userEmail": "another#email.com",
"userQuestion": "Another question?",
"solved": false
}
],
{
"id": 149,
"userName": "test",
"userEmail": "test#test.com",
"userQuestion": "Question ?",
"solved": false
}
]
Here is my service code:
<?php
namespace App\Service;
use App\Entity\Contact;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Serializer\SerializerInterface;
class ContactFile
{
public function __construct(private Filesystem $filesystem, private SerializerInterface $serializer) {}
public function writeContactFile(Contact $contact): void
{
$actualFileContent = file_get_contents('../user-contacts/user-contacts.json');
$requestContent = $this->serializer->serialize($contact, 'json');
$array[] = json_decode($actualFileContent, true);
$array[] = json_decode($requestContent, true);
$result = json_encode($array, JSON_PRETTY_PRINT);
$this->filesystem->remove(['file', '../user-contacts/', 'user-contacts.json']);
$this->filesystem->appendToFile('../user-contacts/user-contacts.json', $result);
}
}
How would you append this "Contact" object to the user-contacts.json file, while having a standard JSON format?
As Cbroe said:
I replaced $array[] = json_decode($actualFileContent, true); to $array = $actualFileContent;
And now it's working. Thank you.
This is a long post, sorry in advance.
I have a couple of questions regarding the diagram below.
How do I create a relationship for these tables? (tried "belongsToMany" and "hasMany")
Should I use Eloquent or Query Builder to get desired result? (image is attached below for desired result)
Is "client_order_items" a pivot table?
How can you distinguish a pivot table? Is it because the table has multiple
foreign keys?
How can I access "images" table from "Manufacturer" model? Can "hasOneThrough / hasManyThrough" achieve this?
Is the desired result achievable purely using Eloquent or DB Query?
//sample:
Manufacturers::find(2)->client_order_items->cars->images->car_image
I tried considering "client_order_items" as a pivot table then making relationships using "belongsToMany" in "Manufacturer", "Car" and "ClientOrder" models.
// App\Model\Manufacturer.php
public function client_orders() {
return $this->belongsToMany(ClientOrder::class,
"client_order_items", "manufacturer_id", "client_order_id")
->withPivot('id', 'quantity', 'car_id');;
}
public function cars() {
return $this->belongsToMany(Car::class,
"client_order_items", "manufacturer_id", "car_id");
}
// App\Model\Car.php
public function client_orders() {
return $this->belongsToMany(ClientOrder::class,
"client_order_items", "car_id", "client_order_id");
}
public function manufacturers() {
return $this->belongsToMany(Manufacturer::class,
"client_order_items", "car_id", "manufacturer_id");
}
// App\Model\ClientOrder.php
public function cars() {
return $this->belongsToMany(Manufacturer::class,
"client_order_items", "client_order_id", "car_id");
}
public function manufacturers() {
return $this->belongsToMany(Manufacturer::class,
"client_order_items", "client_order_id", "manufacturer_id");
}
I also tried "hasMany" relationship:
// App\Model\Manufacturer.php
public function client_order_items() {
return $this->hasMany(ClientOrderItems::class);
}
// App\Model\Cars.php
public function client_order_items() {
return $this->hasMany(ClientOrderItems::class);
}
// App\Model\ClientOrder.php
public function client_order_items() {
return $this->hasMany(ClientOrderItems::class);
}
// App\Model\ClientOrderItems.php
public function car() {
return $this->belongsTo(Car::class);
}
public function manufacturer() {
return $this->belongsTo(Manufacturer::class);
}
public function client_order() {
return $this->belongsTo(ClientOrder::class);
}
My goal is to get the result if i did something like this:
// Manufacturer::find(2)->client_orders
// Desired Result:
[
{
"client_order_id": 88062,
"first_name": "Clark",
"last_name": "Kent",
"order_items": [
{
"client_order_item_id": 37394,
"quantity": 1,
"car_id": 68,
"image": "path_img1"
}
]
},
{
"client_order_id": 60978,
"first_name": "Bruce",
"last_name": "Wayne",
"order_items": [
{
"client_order_item_id": 79913,
"quantity": 1,
"car_id": 68,
"image": "path_img1"
},
{
"client_order_item_id": 84743,
"quantity": 1,
"car_id": 95,
"image": "path_img2"
}
]
}
]
But the result I'm currently getting (with "belongsToMany") is:
// Manufacturer::find(2)->client_orders
// Current Result:
[
{
"id": 88062,
"first_name": "Clark",
"last_name": "Kent",
"pivot": {
"manufacturer_id": 2,
"client_order_id": 88062,
"id": 37394,
"quantity": 1,
"car_id": 68
}
},
{
"id": 60978,
"first_name": "Bruce",
"last_name": "Wayne",
"pivot": {
"manufacturer_id": 2,
"client_order_id": 60978,
"id": 79913,
"quantity": 1,
"car_id": 68
}
},
{
"id": 60978,
"first_name": "Bruce",
"last_name": "Wayne",
"pivot": {
"manufacturer_id": 2,
"client_order_id": 60978,
"id": 84743,
"quantity": 1,
"car_id": 95
}
}
]
Sorry again for the long post.
Thank you in advance.
After experimenting and reading for couple of hours, I was able to get the result I want.
Making the relationships:
Manufacturer model has "belongsToMany" relationship with "ClientOrder"
// App\Model\Manufacturer
public function client_orders() {
return $this->belongsToMany(ClientOrder::class, 'client_order_items', 'manufacturer_id', 'client_order_id');
}
"Car" and "Image" model has "hasMany" relationship. This will give us access to "Image" model from "ClientOrderItems" model.
// App\Models\Car
public function image() {
return $this->belongsTo(Image::class);
}
// App\Models\Image
public function cars() {
return $this->hasMany(Car::class);
}
Creating Accessors to Models
In "ClientOrder" model, create an accessor for the "order_items" key. This will fetch rows from "OrderLineItems" that are related to the "manufacturer_id" and "client_order_id".
// App\Models\ClientOrder
protected $appends = ["order_items"];
public function getOrderItemsAttribute() {
$items = ClientOrderItems::where("manufacturer_id", '=', $this->pivot->manufacturer_id)
->where("client_order_id","=",$this->pivot->client_order_id)
->select(["id as client_order_item_id","car_id","quantity"])
->get();
return $items;
}
In "ClientOrderItems" pivot model, create an accessor for the "image".
// App\Models\ClientOrderItems
protected $appends = ["image"];
public function getImageAttribute() {
return Car::find($this->car_id)->image->car_image;
}
The result of the 2 codes above looks something like this:
[
{
"client_order_item_id": 79913,
"quantity": 1,
"car_id": 68,
"image": "path_img1"
},
{
"client_order_item_id": 84743,
"quantity": 1,
"car_id": 95,
"image": "path_img2"
}
]
More on Accessors & Mutators:
https://laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutators
Retrieving Records
To get the "client orders" that are related to manufacturer_id, use:
/// App\Http\Controllers\ManufacturerController;
public function index() {
$client_order = Manufacturer::find($manufacturer_id)->client_orders->unique("id")->values();
}
Above code will only fetch unique rows from "client_orders" table. Appending the related "order_items" for each row with the help of accessors.
[
{
"client_order_id": 88062,
"first_name": "Clark",
"last_name": "Kent",
"order_items": [
{
"client_order_item_id": 37394,
"quantity": 1,
"car_id": 68,
"image": "path_img1"
}
]
},
{
"client_order_id": 60978,
"first_name": "Bruce",
"last_name": "Wayne",
"order_items": [
{
"client_order_item_id": 79913,
"quantity": 1,
"car_id": 68,
"image": "path_img1"
},
{
"client_order_item_id": 84743,
"quantity": 1,
"car_id": 95,
"image": "path_img2"
}
]
}
]
When returning Std class type object, the error is showing. I'm using PHP 7 and the Laravel 7.0
The error is returning from the setData function of JsonResponse.php (Illuminate\Http)
the setData function using DEFAULT_ENCODING_OPTIONS = 15. this is the reason for that issue
I have no way to fix this issue, but i tried to change JsonResponse setData method $this->encodingOptions into JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE.
Now the error resolved. but I need another way to fix this.
public function setData($data = [])
{
$this->original = $data;
if ($data instanceof Jsonable) {
$this->data = $data->toJson($this->encodingOptions);
//$this->data = json_encode($data->jsonSerialize(), JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE); // LINE NO: 01
} elseif ($data instanceof JsonSerializable) {
$this->data = json_encode($data->jsonSerialize(), $this->encodingOptions);
//$this->data = json_encode($data->jsonSerialize(), $this->encodingOptions); // LINE NO: 02
} elseif ($data instanceof Arrayable) {
$this->data = json_encode($data->toArray(), $this->encodingOptions);
} else {
$this->data = json_encode($data, $this->encodingOptions);
//$this->data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE); // LINE NO: 03
}
if (!$this->hasValidJson(json_last_error())) {
throw new InvalidArgumentException(json_last_error_msg());
}
return $this->update();
}
Uncomment line no 1,2,3 error resolved !
I need another way to fix this. because, after run, composer install that change dismissing...
this is part of my retrieving json
{ "cart": [
{
"id": "a9756db0d79a11ea96c7cf86f7c6e0ee",
"book_id": "81180660d2ed11eaa5299b806f9af290",
"user_customer_user_id": "437a2b60d23611ea942efb15df219288",
"status": "ACTIVE",
"book": {
"id": "81180660d2ed11eaa5299b806f9af290",
"user_admin_user_id": "9c80e8006d5b11e9bb9835ecbe2a229e",
"publisher_id": "7b0d3ac0d6ec11ea8cb15deb159804b0",
"printed_price": 319,
"purchase_link": "no",
"description": "no",
"pages": -1,
"rating_value": 0,
"file_type": "e-pub",
"revenue_split_type": "OP",
"book_authors": [
{
"user_id": "a6d99c206d5b11e9af1a4bbf4f149b08",
"reference_no": "XN87397509",
"description": null,
"search_tags": null,
"bank_name": null,
"account_number": null,
"user": {
"id": "a6d99c206d5b11e9af1a4bbf4f149b08",
"name": "Anton Dias",
"email": "Anton Dias#email.com",
"country_code": null,
"contact_number": null,
"status": "ACTIVE"
}
},
{
"user_id": "aa45c0206d5b11e9941ae50cf510f0f3",
"reference_no": "EB26705547",
"description": null,
"search_tags": null,
"bank_name": null,
"account_number": null,
"user": {
"id": "aa45c0206d5b11e9941ae50cf510f0f3",
"name": "K.G.Karunathilake",
"email": "K.G.Karunathilake#email.com",
"country_code": null,
"contact_number": null,
"status": "ACTIVE"
}
}
],
"book_images": [
{
"book_id": "81180660d2ed11eaa5299b806f9af290",
"type": "LIST",
"size": 0.67
},
{
"book_id": "81180660d2ed11eaa5299b806f9af290",
"type": "PROFILE",
"size": 0.67
}
],
"promotions": []
}
}
]
}
In one of my applications I get a JSON format data from php. Which is as similar as the following:
{
"abc#mail.com": {
"RequestSessions": [
{
"StartAt": "2020-03-29T05:18:37.973618Z",
"RunTime": 292,
"Captcha": 3,
"TotalBidRequests": 40,
"TotalSearchRequests": 2831,
"TotalTradeRequests": 88
}
],
"ProfitSessions": [
{
"StartAt": "2020-03-29T13:56:11.8250985Z",
"Profit": 42598,
"EProfit": 3350,
"Coins": 55674,
"Ecoins": 28000
}
]
},
"adc#mail.com": {
"RequestSessions": [
{
"StartAt": "2020-03-29T05:18:37.973618Z",
"RunTime": 292,
"Captcha": 3,
"TotalBidRequests": 40,
"TotalSearchRequests": 2831,
"TotalTradeRequests": 88
}
],
"ProfitSessions": [
{
"StartAt": "2020-03-29T13:56:11.8250985Z",
"Profit": 42598,
"EProfit": 3350,
"Coins": 55674,
"Ecoins": 28000
}
]
}
}
From this response, I just need to fetch email to process further operations in my application. But I can't identify how to decode this using PHP json_decode()
Can anyone tell me how can I decode this using PHP and fetch only email from this response?
Thanks
In that JSON, the email addresses are the keys of the object - i.e. the names of the properties. If you decode the JSON into an associative array you can get those values using PHP's array_keys function:
$data = json_decode($json, true);
foreach (array_keys($data) as $key)
{
echo $key.PHP_EOL;
}
This outputs:
abc#mail.com
adc#mail.com
Demo: http://sandbox.onlinephpfunctions.com/code/d7890691a6baae9f9314c727a9ad0f6519214a10
I wan to divide fetched a single column from database in three different columns.
The below code gives me one column image_url.
public function fetch()
{
$model = Image::select('image_url');
return Datatables::eloquent($model)->make(true);
}
I want to split this column into three columns before returning it.
as for now it is returned in this form..
{
"draw": 0,
"recordsTotal": 16,
"recordsFiltered": 16,
"data": [
{
"image_url": "public/uploaded_images/2019_08_27_WheatMaizeBanner_1.png"
},
{
"image_url": "public/uploaded_images/2019_08_27_WheatFlourBanner1.jpg"
},
{
"image_url": "public/uploaded_images/2019_08_27_TurDalBanner1.jpg"
},
{
"image_url": "public/uploaded_images/2019_08_27_TurBanner1.png"
}
]
}
But I want something like this
{
"draw": 0,
"recordsTotal": 16,
"recordsFiltered": 16,
"data": [
{
"image1": "public/uploaded_images/2019_08_27_WheatMaizeBanner_1.png",
"image2": "public/uploaded_images/2019_08_27_WheatFlourBanner1.jpg"
"image3": "public/uploaded_images/2019_08_27_TurBanner1.png"
}
]
}
try this:
public function fetch()
{
$model = Image::select('image_url');
$result = Datatables::eloquent($model)->make(true);
$data = [];
foreach($result->data as $i => $record) {
$data['image' . ($i+1)] = $record->image_url;
}
$result->data = [ (object)$data ];
return $result
}