I'm just to do some try to visualize data of mysql table filled with factory faker fzaninotto.
This is my factory file:
$factory->define(Boat::class, function (Faker $faker) {
return [
'name'=> $faker -> name,
'images' => json_encode(["description" => $faker->sentence($nbWords = 2, $variableNbWords = true),
"url" => $faker->imageUrl($width = 800, $height = 600, 'cats', true, 'Faker', true),
"sortOrder" => $faker->randomDigitNotNull]
),
];
This is schema for migration:
public function up()
{
Schema::create('boats', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->json('images');
$table->timestamps();
});
Cotroller fuction:
public function listBoats()
{
$data = Boat::all();
return view('frontendViews.listBoats',['data'=>$data]);
}
Now i can access data with {{$boat->name}} for get name of boat, but how can i get url for src link of images?
'name'=> $faker -> name,
'images' => json_encode(["description" => $faker->sentence($nbWords = 2, $variableNbWords = true),
"url" => $faker->imageUrl($width = 800, $height = 600, 'cats', true, 'Faker', true),
"sortOrder" => $faker->randomDigitNotNull]
),
Thank you
Since you're using {{ $boat->name }}
to access the name, then you could use {{ $boat->images }}
to access the JSON formatted string of the image
Since the images are stored in database in JSON format (as you described), then the JSON formatted string should look like this:
{
"description" : "this is the image of a car",
"url" : "https://somewhere.com/img/car.png",
"sortOrder" : 1
}
In order to access the URL, you need to "decode"/"deserialize"/"parse" the JSON, and then take the "URL" key/property
In native PHP, you do JSON serialization and deserialization with json_encode()
and json_decode()
Therefore, in order to get the image URL: {{ json_decode($boat->images, true)["url"] }}
If you need reference about JSON format:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.