Reputation: 3
I have imported an SQL file into my database and have migrated it as such...
public function up()
{
Schema::create('pokemon', function (Blueprint $table) {
$table->string('id');
$table->string('name');
$table->json('types');
$table->string('height');
$table->string('weight');
$table->json('abilities');
$table->json('eggGroups');
$table->json('stats');
$table->string('genus');
$table->string('description');
$table->boolean('captured');
});
}
The issue I am having is utilizing the "abilities" and "stats" tables, since those were imported as array and object. I would like to be able to utilize the arrays and objects from those tables in my frontend. How can I properly serve those through my API. Right now, all I'm getting back are strings that look like arrays/objects.
Pokemon resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Pokemon extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'types' => $this->types,
'height' => $this->height,
'weight' => $this->weight,
'abilities' => $this->abilities,
'eggGroups' => $this->eggGroups,
'stats' => $this->stats,
'genus' => $this->genus,
'description' => $this->description,
'captured' => $this->captured,
];
}
};
Pokemon controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Pokemon;
use App\Http\Resources\Pokemon as PokemonResource;
class PokemonController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$searched_pokemon = Pokemon::where('name', 'LIKE', ("%" . $request->input('name') . "%"))->paginate(12);
return PokemonResource::collection($searched_pokemon);
}
}
Image of the sql database entries
Upvotes: 0
Views: 62
Reputation: 1577
I think you should use Attribute casting in laravel Array & JSON casting.
Upvotes: 1