I'm quite new to Laravel.
I have no DB connection but I'm trying to separate the logic in the Controllers placing it in the Model in order to create fat models and slim controllers.
When doing it I realized I have to make use of common functions in different models. I've seen they usually place those classes in a app\lib\, but I guess that's just for controllers to access them? I can not seem to access them from m model:
<?php
//in app/lib/MyLog.php
class MyLog{
//whatever
}
Then in m model:
//in a model
MyLog::setLogApi($url);
The error I'm getting:
PHP Fatal error: Class 'MyLog' not found in C:\inetpub\wwwroot\laravel\app\models\Overview.php on line 80
If you include your Model like this in your Controller use App\MyLog;
Then You should have the MyLog.php file inside app\MyLog.php
Update : As the OP wants to access some common functions from any Model
Then Mutators should help you do that
Here is the similar example given over there
public function convertToLower($value)
{
$this->attributes['yourLowerString'] = strtolower($value);
}
Ensure that your model has a namespacing. If your MyLog class has a namespace e.g.:
<?php namespace App\Logging;
class MyLog {
}
Then you can call that in your controller as follows:
<?php namespace App\Controllers;
use App\Logging\MyLog as MyLog;
class MyController {
protected $logger;
public function __construct() {
$this->logger = new MyLog;
}
}
It could be possible that you have to do a composer dump-autoload. This maps namespaces and classes to the right files.
You should use namespaces, it's good practice for modern PHP.
File app/lib/MyLog.php
namespace App\Lib;
class MyLog {
// class functions
}
File /app/models/Overview.php
namespace App\Models;
use App\Lib\MyLog;
class Overview {
// class functions
}
You can use short aliases for fully namespaced classes. Aliases are stored in /app/config/app.php, find part
"aliases" => array(
'App' => 'Illuminate\Support\Facades\App',
.
.
. );
At the end of array add your new alias for MyLog class:
'MyLog' => 'App\Lib\MyLog'
And now in your /app/models/Overview.php you can use shorter alias:
namespace App\Models;
use MyLog;
class Overview {
// class functions
}
Related
I'm using laravel 8 and I'm trying to use spatie\laravel-analytics, but I'm getting this error
Non-static method Spatie\Analytics\Analytics::fetchMostVisitedPages() should not be called statically
I've tried what people have suggested, but I don't know if I'm missing something. So I'm hoping someone can check it out and let me know.
Here is my code
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Spatie\Analytics\Analytics as Analytics;
use Spatie\Analytics\Period;
class GoogleReportController extends Controller
{
public function index()
{
$test = Analytics::fetchMostVisitedpages(Period::days(7));
dd($test);
}
}
As you can see in the source the class methods of Analytics are not static so you cannot call them statically. It's intended to be used as a singleton (and there's good reasons for that). Laravel offers Facades as "wrappers" to singleton classes to allow a static-like access and in the case of this library you can utilise one as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Http;
use Spatie\Analytics\AnalyticsFacade as Analytics; //Change here
use Spatie\Analytics\Period;
class GoogleReportController extends Controller
{
public function index()
{
$test = Analytics::fetchMostVisitedpages(Period::days(7));
dd($test);
}
}
I have created a simple controller and define a function. But when i run this it returns an error that controller does not exist.
In my web.php assign a route.
<?php
Route::get('/', function () { return view('front.welcome'); });
Route::get('plan','PlanController#PlanActivity')->name('plan');
On otherside in my controller my code:
<?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller as BaseController;
use Illuminate\Http\Request;
class PlanController extends Controller {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}
This controller created on App\Http\Controllers\Front - on front folder
Error :
ReflectionException (-1)
Class App\Http\Controllers\PlanController does not exist
Add Front part to:
Route::get('plan', 'Front\PlanController#PlanActivity')->name('plan');
Also, change the top of the controller to:
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
And run composer du.
From the docs:
By default, the RouteServiceProvider includes your route files within a namespace group, allowing you to register controller routes without specifying the full App\Http\Controllers namespace prefix. So, you only need to specify the portion of the namespace that comes after the base App\Http\Controllers namespace.
First when defining route, make sure to use the correct path for the controller. the correct is:
Route::get('plan','Front/PlanController#PlanActivity')->name('plan');
Second you have imported Controller Class as BaseController. so you should extends BaseController not Controller:
class PlanController extends BaseController {
public function PlanActivity()
{
dd("hello");
//return view('admin.index');
}
}
Good day, i'm trying to get the result from my model that called with Mainmodel through my controller, my controller is MainController.
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Mainmodel;
class MainController extends Controller
{
function index(){
echo "Kok, direct akses sih?";
}
function get_menu(){
$menu = app\Mainmodel::request_menu();
dd($menu);
}
}
Here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mainmodel extends Model
{
function request_menu(){
$menu = DB::table('menu')
->orderBy('[order]', 'desc')
->get();
return $menu;
}
}
my routes
Route::get('menu','MainController#get_menu');
with my script above i get this
FatalErrorException in MainController.php line 17: Class
'App\Http\Controllers\app\Mainmodel' not found
how can i fix this ? thanks in advance.
Note: I'm bit confuse with laravel. I'm using codeigniter before. And i have a simple question. In laravel for request to database should i use model ? or can i just use my controller for my request to database.
sorry for my bad english.
I would imagine it's because your using app rather than App for the namespace.
Try changing:
app\Mainmodel
To:
App\Mainmodel
Alternatively, you can add a use statement to the top of the class and then just reference the class i.e.:
use App\Mainmodel;
Then you can just do something like:
Mainmodel::request_menu();
The way you're currently using you models is not the way Eloquent should be used. As I mentioned in my comment you should create a model for each table in your database (or at least for the majority of use cases).
To do this run:
php artisan make:model Menu
Then in the newly created Menu model add:
protected $table = 'menu';
This is because Laravel's default naming convention is singular for the class name and plural for the table name. Since your table name is menu and not menus you just need to tell Laravel to use a different table name.
Then your controller would look something like:
<?php
namespace App\Http\Controllers;
use App\Menu;
class MainController extends Controller
{
public function index()
{
echo "Kok, direct akses sih?";
}
public function get_menu()
{
$menu = Menu::orderBy('order', 'desc')->get();
dd($menu);
}
}
Hope this helps!
You can solve it by different solution. The solution is you don't have to call request_menu(); you can get it in your controller.
MainController
use use Illuminate\Support\Facades\DB;
public function get_menu(){
$menu = DB::table('menu')
->orderBy('Your_Field_Name', 'DESC')
->get();
dd($menu);
}
I am beginner in laravel. And I am using Laravel 5.0.16 in my wamp server. I have been learning laravel by free video tutorial available in laracasts.com. I have been trying to fetch data from database. I have checked that my app is already connected to database.
I do have below structure in app folder:
-app
-Http(folder)
-Other folders (folder)
-Article.php (file)
-User.php (file)
In side Http folder:
-Controllers (folder)
-Middleware (folder)
-Requests (folder)
-Kernel.php (file)
-routes.php (file)
In Controllers folder:
-ArticleController.php (file)
Below is code in side routes, controllers and model file:
/*routes*/
Route::get('articles','ArticleController#index');
/*Controller file*/
use App\models\Article;
namespace App\Http\Controllers;
use App\Http\Request;
use App\Http\Controllers\Controller;
class ArticleController extends Controller {
public function index()
{
$users = Article::all();
return $users;
}
}
/*Model file - Article.php*/
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = 'users';
protected $fillable = ['id','firstname', 'lastname', 'email','reg_date'];
}
Where users is DB table with fields.
I am getting below arror:
FatalErrorException in ArticleController.php line:
Class 'App\Http\Controllers\Article' not found
I have check other SO forums but they didn't help me, can anyone suggest me what am I missing?
There are two issues here. One the namespace declaration should happen before any use statements.
Second your models uses the model namespace but your models aren't in a model directory. The namespace should match the directory structure. So you either need to change the namespace to use App\Article (also change the namespace in the model file) or move the model files into a models directory.
So to fix this without moving files update the code to look like this
namespace App\Http\Controllers;
use App\Article;
use App\Http\Request;
use App\Http\Controllers\Controller;
class ArticleController extends Controller {
public function index()
{
$users = Article::all();
return $users;
}
}
/*Model file - Article.php*/
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = 'users';
protected $fillable = ['id','firstname', 'lastname', 'email','reg_date'];
}
Add this line to the top of a controller:
use App\models\Article;
Or use the full namespace when working with this model:
\App\models\Article::all();
I have decided to use subdirectories for my controllers so that I can manage the application better, but unfortunately I am getting an error,
App
controllers
bdm
LeadController.php
models
LeadsModel.php
this is my LeadController.php code
<?php
namespace bdm;
use Database\Eloquent\Model; //still nothing
class LeadController extends \BaseController
{
}
This is my model code
<?php
class LeadsModel extends Eloquent
{
//code here
}
This is my Route code
Route::group(
array
(
'prefix' => 'bdm'
),
function()
{
Route::get('lead/index','bdm\LeadController#index');
Route::post('lead/get_random_lead','bdm\LeadController#getRandomLead');
}
);
The errors I am getting is:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'bdm\\LeadsModel' not found","file":"C:\\xampp\\htdocs\\holbornasset\\crm\\app\\controllers\\bdm\\LeadController.php","line":55}}
Your LeadsModel is under global namespace. Your LeadController is currently under bdm namespace.
You have two option to call LeadsModel from LeadController
Add namespace bdm to your LeadsModel
Use backslash \ to access LeadsModel
\LeadsModel::find(...);