Laravel 5 cannot call DB::table() directly outside a class - php

In my public/index.php of a Laravel 5 application, I have to query some fields in my database, so I used DB::talbe() to do that.
But it returns error:
Fatal error: Class 'DB' not found in C:\xampp\htdocs\oceanboost\public\index.php on line 49
The code I used to call is:
$_active_plugins = DB::table("option")->where("key", "_active_plugins")->first();
I tried to use
$_active_plugins = \DB::table("option")->where("key", "_active_plugins")->first();
but the same error
And here is my full code of public/index.php
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* #package Laravel
* #author Taylor Otwell <taylorotwell#gmail.com>
*/
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/
require __DIR__.'/../bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$_active_plugins = DB::table("option")->where("key", "_active_plugins")->first();
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
My question is how to call built-in classes like DB in a file when this file is not a class

It's not possible to use the DB facade at that point. The whole database component is booted from the Kernel at this part:
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
Before that it's not available.
What you should do, is create a Service Provider for that. I won't go into all the details but you basically add a class that has a register and an optional boot method. You can create one with an artisan command:
php artisan make:provider PluginServiceProvider
In there you can use the DB facade like you want to. Then you just need to register that provider in config/app.php by adding it to the long providers array and your code will run before any routing or such happens.
Note that you should put your code into the boot method since this one is called after all other providers have been registered.

#Nguyen, if I am not mistaking, I think you are trying to query the database in the public/index.php, which is a very big mistake when considering MVC Frameworks.
Please to do this, you should query your database in a controller then pass the results to a view which will be returned to the index.php.
And if you are in a dilemma, see laravel docs

Related

Call to undefined method App\Charts\SampleChart::labels(), chartjs

I'm currently doing the dashboard in our project and can't progress because of this error. Call to undefined method App\Charts\SampleChart::labels(). I suspect that I missed some installation and configurations but I've done it several times now.
SampleChart.php
<?php
declare(strict_types = 1);
namespace App\Charts;
use Chartisan\PHP\Chartisan;
use ConsoleTVs\Charts\BaseChart;
use Illuminate\Http\Request;
class SampleChart extends BaseChart
{
/**
* Handles the HTTP request for the given chart.
* It must always return an instance of Chartisan
* and never a string or an array.
*/
public function handler(Request $request): Chartisan
{
return Chartisan::build()
->labels(['First', 'Second', 'Third'])
->dataset('Sample', [1, 2, 3])
->dataset('Sample 2', [3, 2, 1]);
}
}
dashboardcontroller
<?php
namespace App\Http\Controllers;
use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Models\ratings;
class DashboardController extends Controller
{
public function dashboard() {
$rating = ratings::all();
$chart = new SampleChart;
$chart->labels(['One', 'Two', 'Three']);
$chart->dataset('My Dataset 1', 'line', [1,2,4]);
return view('user/admin/dashboard', compact('rating'));
}
}
charts.php
<?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Global Route Prefix
|--------------------------------------------------------------------------
|
| This option allows to modify the prefix used by all the chart routes.
| It will be applied to each and every chart created by the library. This
| option comes with the default value of: 'api/chart'. You can still define
| a specific route prefix to each individual chart that will be applied after this.
|
*/
'global_route_prefix' => 'api/chart',
/*
|--------------------------------------------------------------------------
| Global Middlewares.
|--------------------------------------------------------------------------
|
| This option allows to apply a list of middlewares to each and every
| chart created. This is commonly used if all your charts share some
| logic. For example, you might have all your charts under authentication
| middleware. If that's the case, applying a global middleware is a good
| choice rather than applying it individually to each chart.
|
*/
'global_middlewares' => ['web'],
/*
|--------------------------------------------------------------------------
| Global Route Name Prefix
|--------------------------------------------------------------------------
|
| This option allows to modify the prefix used by all the chart route names.
| This is mostly used if there's the need to modify the route names that are
| binded to the charts.
|
*/
'global_route_name_prefix' => 'charts',
];
i followed this site just like what creators on youtube tells: https://charts.erik.cat/guide/installation.html
what could be the problem? please help
It looks like you are trying to call ->labels() on an instance of SampleChart based on the principle of multi-inheritance in php. The problem with that here is that ->labels() is a method of Chartisan class not SampleChart or BaseChart which it extends, hence the error you get (basically just saying hey, I cannot find labels()).
See this answer for an explanation of multi-level inheritance in PHP.
More info: https://www.php.net/manual/en/language.oop5.inheritance.php
I'm curious what your use case for doing this in your controller is though. If it is for rendering, the docs you provided has this: https://charts.erik.cat/guide/render_charts.html

Laravel Route Model Binding - Resource Controller [duplicate]

I have been using RESTful controllers in my Laravel project. By including:
Route::controller('things', 'ThingController')
in my routes.php, I can define functions in the ThingController like:
public function getDisplay($id) {
$thing = Thing::find($id)
...
}
so that GETting the URL "...things/display/1" would automatically be directed to the controller function. This seems pretty handy and has been working great for me so far.
I noticed many of my controller functions start with getting a model by id from the url, and I thought it would be nice to be able to use route model binding to do this for me instead. So I updated my routes.php to
Route::model('thing', 'Thing');
Route::controller('things', 'ThingController')
and changed the ThingController functions to
public function getDisplay($thing) {
...
}
I assumed this would magically work the way I wanted it to (like everything else I've tried so far in Laravel has) but unfortunately I get "Trying to get property of non-object" when I attempt to use $thing in the function. Is this something that should be able to work and I have just done it wrong, or can route model binding only work with routes explicitly named in routes.php?
If you don't mind with URI path, method name and just work only show, edit and update method, you can use Resource Controller to generate URI string which can define model binding.
In routes.php change to
Route::model('things', 'Thing');
Route::resource('things', 'ThingController');
You can use php artisan routes command to see all URIs
$ artisan routes | grep ThingController
GET|HEAD things | things.index | ThingController#index
GET|HEAD things/create | things.create | ThingController#create
POST things | things.store | ThingController#store
GET|HEAD things/{things} | things.show | ThingController#show
GET|HEAD things/{things}/edit | things.edit | ThingController#edit
PUT things/{things} | things.update | ThingController#update
PATCH things/{things} | | ThingController#update
After that you can threat parameter as Thing object without explicitly name route.
/**
* Display the specified thing.
*
* #param Thing $thing
* #return mixed
*/
public function show(Thing $thing)
{
return $thing->toJson();
}
If you want to access ThingController#show, pass your model ID and Laravel will retrieve it automatically.
http://example.com/things/1
{"id":1,"type":"Yo!"}
You can use Route:resource and still provide other methods. Place the route you need just before that particular Route::resource line.
Eg:
Route::model('things', 'Thing');
Route::get('things/{things}/owner', 'ThingController#getOwner');
Route::resource('things', 'ThingController');
Then create the corresponding method in your controller.
public function getOwner($things) {
return Response::json($things->owner()->get());
}
Here is the official documentation from the Laravel 4.2 docs:
Source: http://laravel.com/docs/controllers#resource-controllers
Adding Additional Routes To Resource Controllers
If it becomes necessary for you to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:
Route::get('photos/popular');
Route::resource('photos', 'PhotoController');

Laravel SAML (laravel-saml2) - Config Issues

I'm trying to get SSO working on an application, first time doing anything with this type of thing and falling at first hurdle.
Having some basic issues getting started here. Not totally sure where I am going wrong.
Trying to use https://github.com/aacotroneo/laravel-saml2; Running Laravel 5.4 on a development WAMPserver; installed the package fine, added provider and alias information to config/app.php as per all instructions.
If I try to publish the config file, I get no action, no error, just "Publishing Complete" in Composer.
I can copy the saml2_settings.php file to the config directory from the provider directory, and set the parameters there instead, however, no routes work - trying to get the metadata via /saml2/metadata URL just gives me a 404.
Any ideas - new to SAML but this seems just like a standard installation issue.
1) You need to add SAML2_IDP_HOST in env
2) Your url must contan prefix 'routesPrefix' => '/saml2', so your routes looks like below,
/**
* If 'useRoutes' is set to true, the package defines five new routes:
*
* Method | URI | Name
* -------|--------------------------|------------------
* POST | {routesPrefix}/acs | saml_acs
* GET | {routesPrefix}/login | saml_login
* GET | {routesPrefix}/logout | saml_logout
* GET | {routesPrefix}/metadata | saml_metadata
* GET | {routesPrefix}/sls | saml_sls
*/

Laravel 5 routes are not working

I'm migrating from Laravel 4 to Laravel 5.
Only following is working:
Route::get('/some-url', function(){
echo "Some text";
});
Following is not working:
Route::get('/get-customer-info', 'CustomerController#info');
I created the controller in: app\Http\Controllers\CustomerController.php
So, whenever I redirect to a controller, it always set object not found
Here is my controller:
<?php
namespace App\Http\Controllers;
class CustomerController extends Controller
{
function __construct()
{
View::share('root', URL::to('/'));
}
public function info()
{
echo "ok";
}
}
I moved index.php file to the root.
Here is the index.php file on the
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* #package Laravel
* #author Taylor Otwell <taylorotwell#gmail.com>
*/
/*
|--------------------------------------------------------------------------
|Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/
require __DIR__.'/bootstrap/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);

Can route model binding be used with RESTful controllers?

I have been using RESTful controllers in my Laravel project. By including:
Route::controller('things', 'ThingController')
in my routes.php, I can define functions in the ThingController like:
public function getDisplay($id) {
$thing = Thing::find($id)
...
}
so that GETting the URL "...things/display/1" would automatically be directed to the controller function. This seems pretty handy and has been working great for me so far.
I noticed many of my controller functions start with getting a model by id from the url, and I thought it would be nice to be able to use route model binding to do this for me instead. So I updated my routes.php to
Route::model('thing', 'Thing');
Route::controller('things', 'ThingController')
and changed the ThingController functions to
public function getDisplay($thing) {
...
}
I assumed this would magically work the way I wanted it to (like everything else I've tried so far in Laravel has) but unfortunately I get "Trying to get property of non-object" when I attempt to use $thing in the function. Is this something that should be able to work and I have just done it wrong, or can route model binding only work with routes explicitly named in routes.php?
If you don't mind with URI path, method name and just work only show, edit and update method, you can use Resource Controller to generate URI string which can define model binding.
In routes.php change to
Route::model('things', 'Thing');
Route::resource('things', 'ThingController');
You can use php artisan routes command to see all URIs
$ artisan routes | grep ThingController
GET|HEAD things | things.index | ThingController#index
GET|HEAD things/create | things.create | ThingController#create
POST things | things.store | ThingController#store
GET|HEAD things/{things} | things.show | ThingController#show
GET|HEAD things/{things}/edit | things.edit | ThingController#edit
PUT things/{things} | things.update | ThingController#update
PATCH things/{things} | | ThingController#update
After that you can threat parameter as Thing object without explicitly name route.
/**
* Display the specified thing.
*
* #param Thing $thing
* #return mixed
*/
public function show(Thing $thing)
{
return $thing->toJson();
}
If you want to access ThingController#show, pass your model ID and Laravel will retrieve it automatically.
http://example.com/things/1
{"id":1,"type":"Yo!"}
You can use Route:resource and still provide other methods. Place the route you need just before that particular Route::resource line.
Eg:
Route::model('things', 'Thing');
Route::get('things/{things}/owner', 'ThingController#getOwner');
Route::resource('things', 'ThingController');
Then create the corresponding method in your controller.
public function getOwner($things) {
return Response::json($things->owner()->get());
}
Here is the official documentation from the Laravel 4.2 docs:
Source: http://laravel.com/docs/controllers#resource-controllers
Adding Additional Routes To Resource Controllers
If it becomes necessary for you to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:
Route::get('photos/popular');
Route::resource('photos', 'PhotoController');

Categories