Home > Software engineering >  How to load JSON file into Laravel (controller and route)
How to load JSON file into Laravel (controller and route)

Time:11-03

I'm new to Laravel and trying to load a JSON file into my project (which will then be used for a search function). NEW EDIT *** It is giving me an error of "undefined constant "data""

For my Controller.php I have:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
  public function index() {
    $results = file_get_contents("http://ftp.ebi.ac.uk/pub/databases/genenames/hgnc/json/locus_groups/protein-coding_gene.json");
    $data = json_decode($results, true);
    dd($data);
    }
  }

And for my new edited route per response below web.php I have: (still has the laravel given code in here as well).

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;


Route::get('/', function () {
    return view('welcome');
});


Route::get(“data”, [SiteController::class, “index”]);

CodePudding user response:

In your web.php you need import your controller file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;
// in laravel 8 and 9 your need to do this with all your controllers
use App\Http\Controllers\SiteController;


Route::get('/', function () {
    return view('welcome');
});


Route::get(“data”, [SiteController::class, “index”]);

CodePudding user response:

Your route appears to be incorrect. You want to be referencing your SiteController rather than the base Controller.

use App\Http\Controllers\SiteController;

Route::get('data', [SiteController::class, 'index']);

Don’t forget to include a use statement at the top of your web.php for your SiteController.

  • Related