Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

laradoel

laradoel

Member Since 3 Months Ago

Experience Points
4,710
Total
Experience

290 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
12
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
4,710 XP
Nov
25
22 hours ago
Activity icon

Replied to JSON Field Order Changes While Saving

I have the same problem, why isn't there any solution for this? it's really annyoing because i need the data the why i store it.

Nov
24
1 day ago
Activity icon

Replied to Converting Array To Xml

Ok Thankyou for helping me!!

Activity icon

Replied to Converting Array To Xml

oh waaw, haha could you explain what this does please? How do i integrate this with my $result.

Activity icon

Replied to Converting Array To Xml

But it doesn't works with array attrubutes and hidden empty data ;{ any tips

Here is the array

{
  "data": {
  "_attributes": {
   "phone": "",
  "username": "",
  "password": ""
  }
 },
"fruits": {
"fruit": []
 }
}

Here is the Xml output.

 <root>
  <data phone="" password="" username=""/>
  <fruits>
    <fruit/>
  </fruits>

Any tips? Thanks!

Activity icon

Replied to Converting Array To Xml

Thanks i will also try this!

Activity icon

Replied to Converting Array To Xml

Thankyou!!! you are awsome

Activity icon

Started a new Conversation Converting Array To Xml

hey guys, iam using the libaray ArrayToXml. i want to be able to tell the converter IF THE ARRAY ELEMENT IS EMPTY DON'T CONVERT IT TO XML.

Example:

The 'password' is empty in this array

  {
    "firstName": "Chuck",
  "lastName": "Norris",
   "age": 75,
   "bio": "Roundhouse kicking asses since 1940",
    "password": ""
 }

and it convert to this

    <?xml version="1.0" encoding="UTF-8"?>
     <root>
     <firstName>Chuck</firstName>
     <lastName>Norris</lastName>
       <age>75</age>
    <bio>Roundhouse kicking asses since 1940</bio> 
    <password></password> 
  </root>

what i want is this. so the 'password element gone'

   <?xml version="1.0" encoding="UTF-8"?>
    <root>
     <firstName>Chuck</firstName>
     <lastName>Norris</lastName>
       <age>75</age>
    <bio>Roundhouse kicking asses since 1940</bio>  
 </root>

so i use the ArrayToXML package.

i can't figure it out. here is my convert function

public function show(Configuration $configuration)
   {
    $result = ArrayToXml::convert($configuration->data, 'root', true, 'UTF-8');
    return response($result)->header('Content-Type', 'text/xml');
   }

Maybe i have to do something in the ArrayToXml.php file. from: https://github.com/spatie/array-to-xml

Activity icon

Replied to Converting Array

yeah it just converts it to to wrong order also when i dd the data. i tried it with my friend, an d it works fan on his system. i think there is something wrong with my sysytem. Thanks for your reply tho.

Activity icon

Replied to Converting Array

Here is my store methode

public function store(Request $request)
   {

    $configuration = new Configuration();
    $configuration->data = json_decode($request->data);
    $configurationSaved = $configuration->save();
    if ($configurationSaved) {
        $response = ApiHelpers::apiResponse(false, 201, 'record saved successfully', null);
        return response()->json($response, 201);
    } else {
        $response = ApiHelpers::apiResponse(true, 400, 'record saving failed', null);
        return response()->json($response, 400);
    }

}

Here is my table

public function up()
   {
    Schema::create('configurations', function (Blueprint $table) {
        $table->id();
        $table->json('data')->nullable();
    });

   }
Activity icon

Replied to Converting Array

Oh i see hmm, very weird when i save the array in the database

{ "firstName": "Chuck", "lastName": "Norris", "age": 75, "bio": "Roundhouse kicking asses since 1940", "password": "noneed" }

i save the array in my database and when i press 'submit it' the database completley changes the order of the array. very weird. ;( and thats why the xml coverts in the wrong order.

Activity icon

Replied to Converting Array

can someone help?

Activity icon

Replied to Converting Array

ant tips?

Activity icon

Started a new Conversation Converting Array

Hey guys,

I just want my array to convert in the right order xml. i don't know why this doesn't work.

here is the array.

{
 "firstName": "Chuck",
"lastName": "Norris",
"age": 75,
"bio": "Roundhouse kicking asses since 1940",
 "password": "noneed"
 }

Here is the xml output

 <root>
  <age>75</age>
   <bio>Roundhouse kicking asses since 1940</bio>
   <lastName>Norris</lastName>
  <password>noneed</password>
  <firstName>Chuck</firstName>
</root>

This is what i use to convert it to. xml. ( i use the library ArrayToXml)

  public function show(Configuration $configuration)
  {

    $result = ArrayToXml::convert($configuration->data, 'root', true, 'UTF-8');

    return response($result)->header('Content-Type', 'application/xml');
  }

I just want it to convert the array to xml to with right ORDER here is what i want from the array above

 <root>
  <firstname>Chuck</firstname>
   <lastname>Norris</lastname>
   <age>75</age>
  <bio>Roundhouse kicking asses since 1940</bio>
  <password>noneed</password>
</root>
Nov
18
1 week ago
Activity icon

Replied to Using Pluck For Xml Converter - Please Help!

{ "config": { "version": 2.1, "general": { "Mode": false, "Level": "cool",

   },

"Here is the example of the de data json that convert to xml. but when converting it start with but the name of the root is also config and the system looks to the config element

now how it is when converting the json to xml

twice

<config>//root
<config>// from the json 

but i only want 1 time config, i need the xml to start with config

Activity icon

Replied to Using Pluck For Xml Converter - Please Help!

using this i got this error DOMException Invalid Character Error

 public function show(Configuration $configuration)
  {
$result = ArrayToXml::convert(array_values($configuration->data), 'config', true, 'UTF-8');

return response($result)->header('Content-Type', 'text/xml');
 }
Activity icon

Replied to Using Pluck For Xml Converter - Please Help!

Thanks for the tip.

do you mean like using it this way?

  public function show(Configuration $configuration)
    {
    $result = ArrayToXml::convert(array_values(config)($configuration->data), 'config', true, 'UTF-8');

    return response()->make($result, 200, ['Content-Type' => 'text/xml']);
   }
Activity icon

Replied to Using Pluck For Xml Converter - Please Help!

Awsome thanks!

But is it possible to just delete the root element? because the root element is now "config". But the json i save that coverts to xml also starts with config and needs to with config because the system looks at the config element.

Now i have twice

i hope you understand what i mean.

Activity icon

Started a new Conversation Using Pluck For Xml Converter - Please Help!

Hello, i have a problem. i use pluck but i got this error. Invalid Character Error

i want to convert json to xml but only the table 'data' iam saving json in 'data' table. but i only want the the 'data' to convert to xml. i use the library arraytoxml

public function show(Configuration $configuration)
 {
$result = ArrayToXml::convert(
    $configuration::all()->pluck('data')->jsonSerialize(), // convert collection to array
    'config', // root element name
    true, // replace spaces by underscore in element's names
    'UTF-8' // encoding
    );

 return response()->make($result, 200, ['Content-Type' => 'text/xml']);
   }

Here is my model

 class Configuration extends Model
   {
use HasFactory;

protected $fillable = [
    'data'
];

public $timestamps = false;

protected $casts = [

    'data' => 'array',
];

public function getLinkAttribute()
{
    return '/api/configurations/' . $this->id;
}

 }

Here is my migration

public function up()
 {
  Schema::create('configurations', function (Blueprint $table) {
    $table->id();
    $table->json('data')->nullable();
  });

  }
Activity icon

Replied to Casting Not Working Please Help!

Hello, i have a new probleme. esay but can't figure it out. i use pluck but i got this error. Invalid Character Error

i want to convert json to xml but only the table 'data' iam saving json in 'data' table. but i only want the the 'data' to convert to xml

public function show(Configuration $configuration)
 {
    $result = ArrayToXml::convert(
        $configuration::all()->pluck('data')->jsonSerialize(), // convert collection to array
        'config', // root element name
        true, // replace spaces by underscore in element's names
        'UTF-8' // encoding
    );

    return response()->make($result, 200, ['Content-Type' => 'text/xml']);
  }

Here is my model

class Configuration extends Model
 {
 use HasFactory;

protected $fillable = [
    'data'
];

public $timestamps = false;

protected $casts = [

    'data' => 'array',
];

public function getLinkAttribute()
{
    return '/api/configurations/' . $this->id;
}

 }

Here is my migration

public function up()
   {
    Schema::create('configurations', function (Blueprint $table) {
        $table->id();
        $table->json('data')->nullable();
    });

  }
Nov
06
2 weeks ago
Activity icon

Replied to How To Use Json_decode In This Code

Thankyou for your respond! i worked this out with @automica. When manually storing the data it works fine but iam using postman for post request. the problem was i forgot this in my store function $configuration->json = json_decode($request->json); . more info and solution read here: https://laracasts.com/discuss/channels/laravel/casting-not-working-please-help?page=1#reply=662198

Thanks again!

Activity icon

Replied to Casting Not Working Please Help!

Yes! I learned a lot!

Activity icon

Replied to Casting Not Working Please Help!

worked! Yes thats it! Thakyou very much for helpen me. have a good day!

Activity icon

Replied to Casting Not Working Please Help!

Ok thanks, almost there!! recieve this back

   <configuration>
    <incrementing>1</incrementing>
      <exists>1</exists>
       <wasRecentlyCreated/>
       <timestamps>1</timestamps>
   </configuration>
Activity icon

Replied to Casting Not Working Please Help!

Thanks!

I think i need the mapping because i recieved back the error DOMException Invalid Character Error

from the array to xml package

      if ($this->isArrayAllKeySequential($array) && ! empty($array)) {

        throw new DOMException('Invalid Character Error');

    }

highlighting below in the show function

'UTF-8' // encoding

    );
Activity icon

Replied to Casting Not Working Please Help!

Finally!!!!!! THANKYOU SO much! is it possible to get rid of the root element or just keep it?

     <root>
        < configuration>
        <id>2</id>
        <mac_address>200000</mac_address>
        <data>
         <age>75</age>
         <bio>Roundhouse kicking asses since 1940</bio>
        <lastName>Norris</lastName>
        <password>noneed</password>
        <firstName>Chuck</firstName>
       </data>
      <created_at>2020-11-06T12:12:29.000000Z</created_at>
      <updated_at>2020-11-06T12:12:29.000000Z</updated_at>
        </configuration>
    </root>
Activity icon

Replied to Casting Not Working Please Help!

@automica this is for only the post request

{
"info": {
	"_postman_id": "7944364a-119b-4351-91a3-e8921fe4eae1",
	"name": "config",
	"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
	{
		"name": "http://127.0.0.1:8000/api/configurations",
		"request": {
			"method": "POST",
			"header": [
				{
					"key": "Content-Type",
					"value": "application/json",
					"type": "text"
				}
			],
			"body": {
				"mode": "formdata",
				"formdata": [
					{
						"key": "mac_address",
						"value": "10000",
						"type": "text"
					},
					{
						"key": "data",
						"value": "{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse kicking asses since 1940\",\n  \"password\": \"noneed\"\n}",
						"type": "text"
					}
				]
			},
			"url": {
				"raw": "http://127.0.0.1:8000/api/configurations",
				"protocol": "http",
				"host": [
					"127",
					"0",
					"0",
					"1"
				],
				"port": "8000",
				"path": [
					"api",
					"configurations"
				]
			},
			"description": "posting new configration"
		},
		"response": []
	}
],
"variable": [
	{
		"id": "baseUrl",
		"key": "baseUrl",
		"value": "http://localhost:3000",
		"type": "string"
	}
],
"protocolProfileBehavior": {}
  }
Activity icon

Replied to Casting Not Working Please Help!

do you mean this?

 {
"info": {
	"_postman_id": "7944364a-119b-4351-91a3-e8921fe4eae1",
	"name": "config",
	"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
	{
		"name": "http://127.0.0.1:8000/api/configurations",
		"request": {
			"method": "POST",
			"header": [
				{
					"key": "Content-Type",
					"value": "application/json",
					"type": "text"
				}
			],
			"body": {
				"mode": "formdata",
				"formdata": [
					{
						"key": "mac_address",
						"value": "10000",
						"type": "text"
					},
					{
						"key": "data",
						"value": "{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse kicking asses since 1940\",\n  \"password\": \"noneed\"\n}",
						"type": "text"
					}
				]
			},
			"url": {
				"raw": "http://127.0.0.1:8000/api/configurations",
				"protocol": "http",
				"host": [
					"127",
					"0",
					"0",
					"1"
				],
				"port": "8000",
				"path": [
					"api",
					"configurations"
				]
			},
			"description": "posting new configration"
		},
		"response": []
	},
	{
		"name": "http://127.0.0.1:8000/api/configurations",
		"protocolProfileBehavior": {
			"disableBodyPruning": true
		},
		"request": {
			"auth": {
				"type": "apikey"
			},
			"method": "GET",
			"header": [],
			"body": {
				"mode": "urlencoded",
				"urlencoded": []
			},
			"url": {
				"raw": "http://127.0.0.1:8000/api/configurations",
				"protocol": "http",
				"host": [
					"127",
					"0",
					"0",
					"1"
				],
				"port": "8000",
				"path": [
					"api",
					"configurations"
				]
			},
			"description": "get all configurations"
		},
		"response": []
	}
],
"variable": [
	{
		"id": "baseUrl",
		"key": "baseUrl",
		"value": "http://localhost:3000",
		"type": "string"
	}
],
"protocolProfileBehavior": {}
 }
Activity icon

Replied to Casting Not Working Please Help!

Ok already had $table->json('data')->nullable();

But i just discoverd something weird.

i use postman for the post request.

 <data>{
   "firstName": "Chuck",
   "lastName": "Norris",
   "age": 75,
   "bio": "Roundhouse kicking asses since 1940",
   "password": "noneed"
     }
 </data>

But i just tried manually inserting the data in the database just with the same array. and it worked!

  <root>
    <configuration>
     <id>2</id>
     <mac_address>20000</mac_address>
    <data>
   <age>75</age>
   <bio>Roundhouse kicking asses since 1940</bio>
   <lastName>Norris</lastName>
  <password>noneed</password>
   <firstName>Chuck</firstName>
 </data>

so i think maybe something is wrong with my store function here it is. in postman i just use post request with key and the value for the formdata

public function store(Request $request)
  {

    $configuration = new Configuration();
    $configuration->data= $request->data;
    $configuration->mac_address = $request->mac_address;
    $configurationSaved = $configuration->save();
    if ($configurationSaved) {
        $response = ApiHelpers::apiResponse(false, 201, 'record saved successfully', null);
        return response()->json($response, 201);
    } else {
        $response = ApiHelpers::apiResponse(true, 400, 'record saving failed', null);
        return response()->json($response, 400);
    }

}
Activity icon

Replied to Casting Not Working Please Help!

Sure after updating the casts in model to 'data' => 'array',

Illuminate\Database\Eloquent\Collection {#1212 ▼
 #items: array:1 [▼
"configuration" => App\Models\Configuration {#1230 ▼
  #fillable: array:2 [▼
    0 => "data"
    1 => "mac_address"
  ]
  #casts: array:1 [▼
    "data" => "array"
  ]
  #connection: "mysql"
  #table: "configurations"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [▼
    "id" => 1
    "mac_address" => "10000"
    "data" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse kicking asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
    "created_at" => "2020-11-06 10:41:18"
    "updated_at" => "2020-11-06 10:41:18"
  ]
  #original: array:5 [▼
    "id" => 1
    "mac_address" => "10000"
    "data" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse kicking asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
    "created_at" => "2020-11-06 10:41:18"
    "updated_at" => "2020-11-06 10:41:18"
  ]
Activity icon

Replied to Casting Not Working Please Help!

Okay, thanks,

I have renamed the column 'data' and changed ->withCasts(['data' => 'array'])

Here is de dd($data)

 #items: array:1 [▼
  "configuration" => App\Models\Configuration {#1230 ▼
  #fillable: array:2 [▶]
  #casts: array:1 [▼
    "data" => "array"
  ]
  #connection: "mysql"
  #table: "configurations"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [▼
    "id" => 1
    "mac_address" => "10000"
    "data" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse 
     kicking asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
    "created_at" => "2020-11-06 10:41:18"
    "updated_at" => "2020-11-06 10:41:18"
     ]
     #original: array:5 [▼
       "id" => 1
      "mac_address" => "10000"
    "data" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse 
    kicking asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
    "created_at" => "2020-11-06 10:41:18"
    "updated_at" => "2020-11-06 10:41:18"
     ]
Activity icon

Replied to Casting Not Working Please Help!

Here is a dd($result)

<root>
 <configuration>
   <id>1</id>
    <mac_address>10000</mac_address>
   <json>{
     "firstName": "Chuck",
     "lastName": "Norris",
      "age": 75,
     "bio": "Roundhouse kicking asses since 1940",
      "password": "noneed"
        }
     </json>
        <created_at>2020-11-06T09:25:40.000000Z</created_at>
           <updated_at>2020-11-06T09:25:40.000000Z</updated_at>
       </configuration>
         </root>

So the edited configuration element worked fine! but 'json' is still in array instead of xml and also how to get rid of the root element?

Activity icon

Replied to Casting Not Working Please Help!

Thankyou for you respond!

so here is a better example. here is what i save in the database doing a dd($data)

Illuminate\Database\Eloquent\Collection {#1212 ▼
#items: array:1 [▼
"config" => App\Models\Configuration {#1230 ▼
#fillable: array:2 [▶]
#casts: array:1 [▼
"json" => "json"
]
#connection: "mysql"
#table: "configurations"
 #primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
 #withCount: []
 #perPage: 15
+exists: true
 +wasRecentlyCreated: false
 #attributes: array:5 [▼
  "id" => 1
  "mac_address" => "10000"
  "json" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse 
 kicking 
  asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
   "created_at" => "2020-11-06 09:25:40"
   "updated_at" => "2020-11-06 09:25:40"
     ]

Here is the xml output now.

 <root>
   <config>
     <id>1</id>
        <mac_address>10000</mac_address>
         <json>{ "firstName": "Chuck", "lastName": "Norris", "age": 75, "bio": "Roundhouse kicking asses since 
            1940", 
               "password": "noneed" }</json>
                  <created_at>2020-11-06T09:25:40.000000Z</created_at>
                     <updated_at>2020-11-06T09:25:40.000000Z</updated_at>
                       </config>
            </root>

This how i actually want the xml to look like

   <configuration>
     <id>1</id>
        <mac_address>10000</mac_address>
        <config>
          <firstname>Chuck</firstname>
         <lastname>Chuck</lastname>
           <age>75</age>
         <bio>Roundhouse kicking asses since 
              1940</bio>
           <password>noneed</password>
              </config>
                  <created_at>2020-11-06T09:25:40.000000Z</created_at>
                     <updated_at>2020-11-06T09:25:40.000000Z</updated_at>
                </configuration>

So with json i save ( $table->json('json'); ). i want the input data separated elements in de xml. in my model i use protected $casts = [ 'json' => 'json', ];

Here is my show controller converting it to xml.

public function show(Configuration $configuration)
  {
$data = Configuration::query()
    ->withCasts(['json' => 'json'])
    ->get()
    ->mapWithKeys(function ($configuration) {
        // replace config with the element you want
        // to wrap each config object: <config>...</config>
        return ['config' => $configuration];
    });

$result = ArrayToXml::convert(
    $data->jsonSerialize(), // convert collection to array
    'root', // root element name
    true, // replace spaces by underscore in element's names
    'UTF-8' // encoding
);

  return response()->make($result, 200, ['Content-Type' => 'text/xml']);
  }
Activity icon

Replied to How To Use Json_decode In This Code

Thankyou for your respond.

here is the dd($data)

Illuminate\Database\Eloquent\Collection {#1212 ▼
 #items: array:1 [▼
"config" => App\Models\Configuration {#1230 ▼
  #fillable: array:2 [▶]
  #casts: array:1 [▼
    "json" => "json"
  ]
  #connection: "mysql"
  #table: "configurations"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:5 [▼
    "id" => 1
    "mac_address" => "10000"
    "json" => ""{\n  \"firstName\": \"Chuck\",\n  \"lastName\": \"Norris\",\n  \"age\": 75,\n  \"bio\": \"Roundhouse kicking 
 asses since 1940\",\n  \"password\": \"noneed\"\n} ▶"
    "created_at" => "2020-11-06 09:25:40"
    "updated_at" => "2020-11-06 09:25:40"
  ]
  #original: array:5 [▶]
  #changes: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
 }
 ]

}

The xml output

   <root>
     <config>
     <id>1</id>
  <mac_address>10000</mac_address>
   <json>{ "firstName": "Chuck", "lastName": "Norris", "age": 75, "bio": "Roundhouse kicking asses since 1940", 
    "password": "noneed" }</json>
   <created_at>2020-11-06T09:25:40.000000Z</created_at>
  <updated_at>2020-11-06T09:25:40.000000Z</updated_at>
   </config>
 </root>

model class

 class Configuration extends Model
   {
  use HasFactory;

protected $fillable = [
    'json', 'mac_address',
];

protected $casts = [
    'json' => 'json',
];

public function getLinkAttribute()
{
    return '/api/configurations/' . $this->id;
}
//    public function getattributesAttribute($value)
//    {
 //        return json_decode($value);
 //    }

  }

controller for converting to xml

public function show(Configuration $configuration)
  {
    $data = Configuration::query()
        ->withCasts(['json' => 'json'])
        ->get()
        ->mapWithKeys(function ($configuration) {
            // replace config with the element you want
            // to wrap each config object: <config>...</config>
            return ['config' => $configuration];
        });

    $result = ArrayToXml::convert(
        $data->jsonSerialize(), // convert collection to array
        'root', // root element name
        true, // replace spaces by underscore in element's names
        'UTF-8' // encoding
    );

    dd($result);

    return response()->make($result, 200, ['Content-Type' => 'text/xml']);
}

so the problem is the casts is not working the json casts should give me the xml separated

like his

<firstname> Chuck</firstname>
  <lastname> Norris</lastname>
 <age> 75</age>

etc etc

Nov
05
2 weeks ago
Activity icon

Replied to How To Use Json_decode In This Code

@rodrigo.pedra. Sorry, replying to the commen - Add a dynamic cast just when querying:

 $data = Configuration::query()
    ->withCasts(['json' => 'json'])
    ->get()
    ->mapWithKeys(function ($configuration) {
        // replace config with the element you want
        // to wrap each config object: <config>...</config>
        return ['config' => $configuration];
     });

''As 1 have a json column that is holding a JSON string, if you want that serialized to XML too you can either''

i tried this with casting it json and also with array. but i still recieve back an array . like this.

  <root>
       <configuration>
     <id>1</id>
  <mac_address>40099</mac_address>
 <json>{
 "config": {
 "version": 2.1,
"general": {
 "test": "true",
     }</json>
    <created_at>2020-11-05T13:09:47.000000Z</created_at>
    <updated_at>2020-11-05T13:09:47.000000Z</updated_at>
   </configuration>
  </root>

i need it be like this.

<root>
    <configuration>
     <id>1</id>
  <mac_address>40099</mac_address>
 <json>
  <version>2.1</version>
   <test>true</test>
   etc 
  </json>
    <created_at>2020-11-05T13:09:47.000000Z</created_at>
    <updated_at>2020-11-05T13:09:47.000000Z</updated_at>
   </configuration>
  </root>
Activity icon

Replied to Casting Not Working Please Help!

Ok thanks, but it doesn't matter if i change the cast to array stil the same output

 protected $casts = [

    // if its name was different you could use:
    // 'another_column' => 'json',
    'config' => 'array',
  ];
<root>
<configuration>
    <id>1</id>
    <mac_address>40099</mac_address>
    <config>{
    "config": {
  "version": 2.1,
  "general": {
  "test": "true",
   }</config>
    <created_at>2020-11-05T13:09:47.000000Z</created_at>
    <updated_at>2020-11-05T13:09:47.000000Z</updated_at>
   </configuration>
 </root>

config is the table in the database saved as json

$table->json('config'); $table->string('mac_address');

Activity icon

Replied to Casting Not Working Please Help!

yes. i want all the array attribute to xml so

  <version>2.1<version>
    <test> teststdata<test>

etc , this should work with casting i thought

Activity icon

Replied to Casting Not Working Please Help!

Yeah thanks. but still weird why my casts is not converting to xml. any idea?

Activity icon

Started a new Conversation Casting Not Working Please Help!

i'am saving json to my database. and i wrote a code to coverting the table to xml. it dosn't covert the casts table to xml why?

here is my show here i convert the json to xml

  public function show(Configuration $configuration)
   {
    $data = Configuration::query()
        ->withCasts(['config' => 'json'])
        ->get()
        ->mapWithKeys(function ($configuration) {
            // to wrap each config object: <config>...</config>
            return ['config' => $configuration];
        });

    $result = ArrayToXml::convert(
        $data->jsonSerialize(), // convert collection to array
        'root', // root element name
        true, // replace spaces by underscore in element's names
        'UTF-8' // encoding
    );

    return response()->make($result, 200, ['Content-Type' => 'text/xml']);
 }

here is my. model

protected $casts = [

    // if its name was different you could use:
    // 'another_column' => 'json',
    'config' => 'json',
   ];

here is the output

<root>
<config>
   <id>1</id>
 <mac_address>1000</mac_address>
 <config>{ "config": { "version": 2.1, "general": { "test": "testdata", "testl": [ "test" ], "flood": } } } 
 </config>
 <created_at>2020-11-05T09:44:38.000000Z</created_at>
  <updated_at>2020-11-05T09:44:38.000000Z</updated_at>
  </config>
  </root>

here is my store controller

  public function store(Request $request)
  {

 $configuration = new Configuration();
$configuration->config = $request->config;
$configuration->mac_address = $request->mac_address;
$configurationSaved = $configuration->save();
if ($configurationSaved) {
    $response = ApiHelpers::apiResponse(false, 200, 'record saved successfully', null);
    return response()->json($response, 200);
} else {
    $response = ApiHelpers::apiResponse(true, 400, 'record saving failed', null);
    return response()->json($response, 400);
}

}
Activity icon

Replied to Casts Not Working

Maybe i need to json_decode while storing here is my store methode

 public function store(Request $request)
  {

    $configuration = new Configuration();
    $configuration->config = $request->config;
    $configuration->mac_address = $request->mac_address;
    $configurationSaved = $configuration->save();
    if ($configurationSaved) {
        $response = ApiHelpers::apiResponse(false, 200, 'record saved successfully', null);
        return response()->json($response, 200);
    } else {
        $response = ApiHelpers::apiResponse(true, 400, 'record saving failed', null);
        return response()->json($response, 400);
    }

  }
Activity icon

Started a new Conversation Casts Not Working

i'am saving json. in the table config. i need to covert it to xml

here is my model

protected $casts = [

    // if its name was different you could use:
    // 'another_column' => 'json',
    'config' => 'json',
    ];

my controller: i'am converting the json to xml.

     public function show(Configuration $configuration)
      {
     $data = Configuration::query()
        ->withCasts(['config' => 'json'])
        ->get()
        ->mapWithKeys(function ($configuration) {
            // to wrap each config object: <config>...</config>
            return ['config' => $configuration];
        });

    $result = ArrayToXml::convert(
        $data->jsonSerialize(), // convert collection to array
        'root', // root element name
        true, // replace spaces by underscore in element's names
        'UTF-8' // encoding
    );

    return response()->make($result, 200, ['Content-Type' => 'text/xml']);
}

Here is my respond. the config part suppost to be in xml too. yesterday it worked. i don't know why the config dosn't covert to xml

 <root>
<config>
<id>1</id>
 <mac_address>1000</mac_address>
 <config>{ "config": { "version": 2.1, "general": { "test": "testdata", "testl": [ "test" ], "flood": } } } 
</config>
<created_at>2020-11-05T09:44:38.000000Z</created_at>
  <updated_at>2020-11-05T09:44:38.000000Z</updated_at>
  </config>
   </root>

maybe i need to try this with json decode?

Nov
04
3 weeks ago
Activity icon

Replied to Saving A Api Converted File

Great! stupid mistake hahah. works fine now! is it also possible to write a code downloding the xml file to your device?

Activity icon

Replied to Saving A Api Converted File

you are amazing!!!!!! THANKYOU!

worked great!

only one thing i don't understand, than i'm done haha.

Ok, i just want to test the download function. so currently i'am listing this in the view

Mac Address Link

44000 /link/to/download/1

12 /link/to/download/2

example: the first link send me to this path: http://127.0.0.1:8000/link/to/download/1

Where do i write the code for download the example the first mac adress.? so if user clicks on a link it wile download the file in xml.

thats the only thing left i don't get.

Activity icon

Replied to Saving A Api Converted File

nicee, let me test this!

Activity icon

Replied to Saving A Api Converted File

yes i'am sorry. i want the complete xml indeed! but i want to list it by all the mac addressen so a user can download the xml file

Activity icon

Replied to Saving A Api Converted File

Thank you! i changed it to

  <div class="form-group py-3 px-4 shadow rounded">

   <label for="mac_address "><h4 class="font-weight-bold">Mac Address:</h4></label>
     <p>{{$result['mac_address']}}</p>
      <label for="configfile"><h4 class="font-weight-bold">configfile:</h4></label>
       <p>{{$result['json']}}</p>

       </div>

but got this error Illegal string offset 'mac_address'

and when i dd($result); the json data is not in xml anymore but in array. hmm..

Activity icon

Replied to How To Use Json_decode In This Code

Thankyou! goodluck with you work!

Activity icon

Replied to Saving A Api Converted File

Thankyou sir! worked great!

and the last issue.. i got this error Trying to get property 'mac_address' of non-object

i changed the return view to: return view('xml', ['result' => $result]);

here is my view thank you for helping, you helped alot!!

 @section('content')

   <div class="container">
    <div class="row">
        <div class="col-12 col-sm-10 col-lg-6 mx-auto">
            <h1 class="display-4" style="text-align: center; margin: 50px 0;">Configuration files</h1>
            <div class="form-group py-3 px-4 shadow rounded">

                <label for="mac_address "><h4 class="font-weight-bold">Mac Address:</h4></label>
                <p>{{$result->mac_address}}</p>
                <label for="configfile"><h4 class="font-weight-bold">configfile:</h4></label>
                <p>{{$result->json}}</p>

            </div>


            </div>
Activity icon

Replied to Saving A Api Converted File

@automica Thankyou for your respond, But i really don't understand what you are doing here.

I thought i needed to list the saved data in a blade a make it possible for a user to download the xml file.

Here is the controller.

public function xml(Configuration $configuration)
 {
    $data = Configuration::query()
        ->withCasts(['json' => 'json'])
        ->get()
        ->mapWithKeys(function ($configuration) {
            // to wrap each config object: <config>...</config>
            return ['config' => $configuration];
        });

    $result = ArrayToXml::convert(
        $data->jsonSerialize(), // convert collection to array
        'root', // root element name
        true, // replace spaces by underscore in element's names
        'UTF-8' // encoding
    );

        // return response()->make($result, 200, ['Content-Type' => 'text/xml']); //  works it shows the xml in txt
   
    return view('xml', ['data' => $result]); // i need to use this one to list the saved data's in my view. 
  }

The output here gives me xml in my view works fine.

but i want to list all the created id's and make it possible for a user to download.

Her is my blade but i got the error: $result is undefined

 @extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-12 col-sm-10 col-lg-6 mx-auto">
            <h1 class="display-4" style="text-align: center; margin: 50px 0;">Configuration files</h1>
            <div class="form-group py-3 px-4 shadow rounded">

                <label for="title "><h4 class="font-weight-bold">Title:</h4></label>
                <p>{{$result->mac_address}}</p>
                <label for="Description"><h4 class="font-weight-bold">Description:</h4></label>
                <p>{{$result->json}}</p>

            </div>
   @endsection