getting class not found error in laravel - laravel

I am working on laravel and following the tutorial http://technetlk.blogspot.com.au/2012/09/laravel-backbonejs-coffeescript_3527.html. currently working on 7th part of this tutorial.
in routes.php I have written
Route::any('api/category/(:num?)',
array('as' => 'api.category',
'uses' => 'api.category#index')
);
In api/category.php,
<?php
class Api_Category_Controller extends Base_Controller
{
public $restful = true;
public function get_index($id = null)
{
if (is_null($id ))
{
$allCats = Category::all();
return BaseModel::allToJson($allCats);
}
else
{
$cat = Category::find($id);
return $cat->toJson();
}
}
public function post_index()
{
$cat = Input::json();
$dbCat = new Category();
$dbCat->code = $cat->code;
$dbCat->name = $cat->name;
$dbCat->save();
return $dbCat->toJson();
}
public function put_index()
{
$cat = Input::json();
$dbCat = Category::find($cat->id);
$dbCat->code = $cat->code;
$dbCat->name = $cat->name;
$dbCat->save();
return $dbCat->toJson();
}
public function delete_index($id = null)
{
$dbCat = Category::find($id);
$dbCat->delete();
}
}
?>
and in BaseModel.php
<?php
class Category extends BaseModel
{
public static $table = 'tbl_category';
}
class BaseModel extends Eloquent
{
public function toJson()
{
return json_encode($this->to_array());
}
public static function allToJson($array)
{
$temp = array();
foreach($array as $t)
{
$temp[] = $t->to_array();
}
return json_encode($temp);
}
}
?>
when I am trying to run
curl -X POST http://lbc.dev/api/category -H "Content-Type: application/json" –d '{"code":"cat1", "name":"Category One"}'
I am getting the follwing error
Unhandled Exception
Message:
Class 'Category' not found Location:
C:\xampp\htdocs\NewBlog\application\controllers\api\category.php on
line 9

Your Category Model should be located in /application/models/category.php
Your BaseModel class should be located in /application/models/basemodel.php
The following is if your BaseModel class is not in a defined Autoloader directory:
Another problem you may face is the BaseModel not autoloading
correctly. This can be fixed by appending this line of code to your
start.php file found in your application folder:
// Autoloader::map
'BaseModel' => path('app').'/path/to/basemodel.php',

U have to specify the model in controller file before using it
Add this line above the following line in your controller file
use App\Category;
class Api_Category_Controller extends Base_Controller
{

Related

Laravel : need a controller to be called on all views

What i want is to load a sidebar with a controller inside, on my layouts/app.blade.php.
i have read that the best way is to load it on AppServiceProvider, so i tried this :
View::composer('layouts.app', function ($view) {
$data = \App\Http\Controllers\DeliveryController::index();
$view::share('Delivery',$data);
});
That works, but the DeliveryController::index gave me this error :
Using $this when not in object context
The way that really works is to forget the AppServiceProviers and to do it on every views controller like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Management\DeliveryManagement;
class WelcomeController extends Controller
{
protected $deliveryManagement;
protected $nbLastsDelivery = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
// $this->middleware('auth');
$this->deliveryManagement = $deliveryManagement;
}
public function index()
{
$deliveries = $this->deliveryManagement->getLasts($this->nbLastsDelivery);
return view ('welcome', compact('deliveries'));
}
}
Unfortunately i think AppServiceProviers is a better way, right ?
If someone can help me i would be very grateful !
EDIT :
I add code of DeliveryController and DeliveryManagement :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\DeliveryRequest;
use App\Management\DeliveryManagement;
class DeliveryController extends Controller
{
protected $deliveryManagement;
protected $nbLasts = 3;
public function __construct(DeliveryManagement $deliveryManagement)
{
$this->deliveryManagement=$deliveryManagement;
}
public function index()
{
$deliveries=$this->deliveryManagement->getLasts($this->nbLasts);
return $deliveries;
}
and :
<?php
namespace App\Management;
use App\Models\Delivery;
class DeliveryManagement extends ResourceManagement
{
protected $delivery;
public function __construct (Delivery $delivery)
{
$this->model=$delivery;
}
public function getLasts($limit)
{
$req = $this->model->orderBy('deliveries.id', 'desc')->skip(0)->take($limit)->get();
$i=0; $render = array();
foreach($req as $delivery)
{
if($i=0)
$render = [$delivery, 'latest'];
else
$render = [$delivery, 'older'];
$i++;
}
return $render;
}
}

PHPUnit test fails with InvalidArgumentException: Unknown formatter with Laravel 8 factory

In my Laravel 8 project, I have this action class:
<?php
namespace App\Actions\Content;
use Illuminate\Support\Facades\Config;
class FixUriAction
{
public function __invoke(string $uri)
{
if (preg_match('/^https?:\/\//i', $uri)) {
return $uri;
}
return '/' . Config::get('current_lang')->code . '/' . $uri;
}
}
I want to write unit tests for this class, now I have this code in my test file:
<?php
namespace Tests\Unit\Actions\Content;
use App\Actions\Content\FixUriAction;
use App\Models\Settings\Lang;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Config;
use PHPUnit\Framework\TestCase;
class FixUriActionTest extends TestCase
{
use DatabaseTransactions;
protected Lang $lang;
protected FixUriAction $action;
public function setUp(): void
{
parent::setUp();
$this->action = new FixUriAction();
$this->lang = Lang::factory()->make();
Config::set('current_lang', $this->lang);
}
public function testShouldPrefixUriWithLangCode(): void
{
$uri = '/a-test-uri';
$expectation = '/' . $this->lang->code . $uri;
$result = ($this->action)($uri);
$this->assertEquals($expectation, $result);
}
}
In my LangFactory I have this code:
<?php
namespace Database\Factories;
use App\Models\Settings\Lang;
use Illuminate\Database\Eloquent\Factories\Factory;
class LangFactory extends Factory
{
protected $model = Lang::class;
public function definition()
{
return [
'name' => $this->faker->country,
'code' => $this->faker->languageCode,
];
}
}
When I run phpunit tests/Unit/Actions/Content/FixUriActionTest.php command it says:
There was 1 error:
1) Tests\Unit\Actions\Content\FixUriActionTest::testShouldPrefixUriWithLangCode
InvalidArgumentException: Unknown formatter "country"
I use PHPUnit 9.5.6 with PHP 7.4, Laravel 8.49
What I miss?
try in this way
<?php
namespace Database\Factories;
use App\Models\Settings\Lang;
use Illuminate\Database\Eloquent\Factories\Factory;
class LangFactory extends Factory
{
protected $model = Lang::class;
public function definition()
{
return [
'name' => $this->faker->country(),
'code' => $this->faker->languageCode(),
];
}
}
it should work
It seems you're using fakerphp library, which doesn't have the country formatter. Instead you can use the country code (2 letters or 3 letters). Check here for further details.
https://fakerphp.github.io/formatters/miscellaneous/#countrycode

How to reuse the same function in multiple policy files

This function will be used by many policies. How to avoid writing this inside each policy file?
public function checkRoleAndPermission($name)
{
$content = 'Location';
$permission = Permission::where([['content', $content], ['name', $name]])->first();
if(empty($permission))
return false;
return auth()->user()->hasRole($permission->roles);
}
The best practice would be to create an BasePolicy and extend all others from it
Example
class BasePolicy
{
public function checkRoleAndPermission($name)
{
$content = 'Location';
$permission = Permission::where([['content', $content], ['name', $name]])->first();
if(empty($permission))
return false;
return auth()->user()->hasRole($permission->roles);
}
}
class PostPolicy extends BasePolicy
{
public function update(User $user, Post $post, $rolePermission)
{
$this->checkRoleAndPermission($rolePermission);
...
}
}
```
Create a class with the above function 'checkRoleAndPermission'.
Wherever need, extend the class and reuse the function like below.
Class A:
public class A{
public function checkRoleAndPermission($name)
{
$content = 'Location';
$permission = Permission::where([['content', $content], ['name', $name]])->first();
if(empty($permission)) return false;
return auth()->user()->hasRole($permission->roles);
}
}
Class B:
use A;
public class B extends A{
$this->checkRoleAndPermission('name'); // it will call class A's checkRoleAndPermission() function
}

Larave 6 l “Creating default object from empty value”

Here, I have setuo CRUD table with laravel, vuetify and vue . I could successfull create and read data from the database. But, for some reason my update and delete are not working. I am getting error like:
{message: "Creating default object from empty value", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php"
line: 53
message: "Creating default object from empty value"
trace: [{file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php", line: 53,…},…]
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$stage= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description,
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code; //line 53
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=> $stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
I just found they you are using uuid as id not increment. that why you get error like that:
to solve your problem you need to add the field to your model;
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
}
I hope this time you can solve your problem. happy coding.
Edit you can read docs for more info

Using Doctrine in Joomla 1.5

I'm trying to use Doctrine in Joomla 1.5 but have not been able to get anything running.
According to this article: http://magazine.joomla.org/issues/issue-may-2011/item/447-using-doctrine-ORM-in-joomla
I immediately get Fatal error: Class 'Fatal error: Call to undefined method JController::getInstance() in /var/www/html/hosts/joomla/public_html/components/com_bugs/bugs.php on line 13
The bugs.php looks like this:
// no direct access
defined('_JEXEC') or die; // Include dependancies
jimport('joomla.application.component.controller');
//require_once(JPATH_LIBRARIES . '/doctrine/vendor/autoload.php');
require_once(JPATH_LIBRARIES . '/doctrine/bootstrap.php');
require_once(JPATH_LIBRARIES . '/doctrine/JoomlaDoctrineBootstrapper.php');
require_once(JPATH_COMPONENT.DS.'controller.php');
//$controller = new BugsController(JRequest::getVar('task', ''));
$controller = JController::getInstance('Bugs');
Not sure how to implement this, when trying to use the $controller = new BugsController the error is: Fatal error: Class 'JController' not found in
This because I have the autoload on in bugs.php and have /public_html/components/com_bugs/controller.php extend /public_html/libraries/doctrine/JoomlaDoctrineBootstrapper.php the JoomlaDoctrineBootstrapper exends JController but JController cannot be found anymore after composer and the autoload did something.
I'm starting to think that it's not possible to use Joomla with Doctrine since Doctrine has to be installed with composer (didn't find any other documentation on how to download and configure it) and composer seems to want everything in vendor so have to put all the Joomla classes in vendor too?
[UPDATE]
It looks like whatever composer does in /public_html/libraries/doctrine/vendor/autoload.php completely breaks jimport('joomla.application.component.controller')
Not including the autoload however gives me another problem, like none of the Doctrine classes are found: Class 'Doctrine\Common\Cache\ArrayCache' not found
Maybe I'll try and hack /public_html/libraries/doctrine/vendor/composer/autoload_real.php to try and see if that one can load Joomla classes for me.
Either jimport or composer won't work because jimport defines __autoload. Instead of __autoload I'm using spl_autoload_register that only seems to work with PHP version starting from 5.1.2.
Changed loader:
/public_html/libraries/loader.php
class JLoader
{
public static function autoload($class)
{
if(JLoader::load($class)) {
return true;
}
return false;
}
//... other code and comments
function import( $filePath, $base = null, $key = 'libraries.' )
{
static $paths;
if (!isset($paths)) {
$paths = array();
//assuming PHP 5 >= 5.1.2
spl_autoload_register(array('JLoader', 'autoload'), true, true);
}
//remove the __autoload function
The bugs.php looks like this:
/public_html/components/com_bugs/bugs.php
<?php
// no direct access
defined('_JEXEC') or die; // Include dependancies
require_once(JPATH_LIBRARIES . '/doctrine/vendor/autoload.php');
require_once(JPATH_LIBRARIES . '/doctrine/bootstrap.php');
require_once(JPATH_LIBRARIES . '/doctrine/JoomlaDoctrineBootstrapper.php');
require_once(JPATH_COMPONENT.DS.'controller.php');
//using links like /index.php?option=com_bugs&format=text&task=save
// defaults to link so above is same as: http://joomla/index.php?option=com_bugs&format=text&task=save&router=link
$route=JRequest::getVar('router', 'Link');
$controllerName = 'bugsController'.$route;
//include the controller
include_once(dirname(__FILE__) . '/controllers/'.$route.".php");
$controller = new bugsControllerlink(JRequest::getVar('task', ''));
$controller->setEntityManager(bootstrapDoctrine());
$controller->execute(JRequest::getVar('task', ''));
$controller->redirect();
/**
* Initialize doctrine by setting the entities and proxies locaties. Also define
* a default namespace for the proxies.
*/
function bootstrapDoctrine() {
$doctrineProxy = new JoomlaDoctrineBootstrapper(JoomlaDoctrineBootstrapper::APP_MODE_DEVELOPMENT);
$doctrineProxy->setEntityLibrary(dirname(__FILE__) . '/models');
$doctrineProxy->setProxyLibrary(dirname(__FILE__) . '/proxies');
$doctrineProxy->setProxyNamespace('Joomla\Proxies');
$doctrineProxy->setConnectionOptions(getConfigurationOptions());
$doctrineProxy->bootstrap();
return $doctrineProxy->getEntityManager();
}
function getConfigurationOptions() { // Define database configuration options
$joomlaConfig = JFactory::getConfig();
return array('driver' => 'pdo_mysql', 'path' => 'database.mysql'
, 'dbname' => $joomlaConfig->getValue("config.data.db")
, 'user' => $joomlaConfig->getValue("config.data.user")
, 'password' => $joomlaConfig->getValue("config.data.password"));
}
?>
The link controller looks like: (file name has start with a capital L)
/public_html/components/com_bugs/controllers/Link.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library (done by composer)
//jimport('joomla.application.component.controller');
class bugsControllerlink extends JoomlaDoctrineBootstrapper{
function __construct()
{
parent::__construct();
$this->registerTask( 'show','show' );
$this->registerTask( 'save','save' );
}
function save(){
$model=$this->getModel('link');
$view = $this->getView('show','text');
$view->setLayout('save');
$model->em=$this->getEntityManager();
$view->data = $model->save();
$view->display();
}
}
Didn't change the boodtrap, that still looks like this:
/public_html/libraries/doctrine/bootstrap.php
<?php
interface JoomlaDoctrineController {
public function setEntityManager(Doctrine\ORM\EntityManager $entityManager);
}
?>
The /public_html/libraries/doctrine/JoomlaDoctrineBootstrapper.php looks like:
<?php
/** * Configuration class to integrate Doctrine into Joomla. *
* #author pderaaij <removed email, check link in question> */
use Composer\Autoload\ClassLoader,
Doctrine\ORM\EntityManager,
Doctrine\ORM\Configuration,
Doctrine\Common\Cache\ArrayCache;
jimport( 'joomla.application.component.controller' );
class JoomlaDoctrineBootstrapper extends JController{
const APP_MODE_DEVELOPMENT = 1;
const APP_MODE_PRODUCTION = 2;
private $applicationMode;
private $cache;
private $entityLibrary;
private $proxyLibrary;
private $proxyNamespace;
private $entityManager;
private $connectionOptions;
public function __construct($applicationMode=1) {
$this->applicationMode = $applicationMode;
$this->_name="bugs";
parent::__construct();
}
public function getConnectionOptions() {
return $this->connectionOptions;
}
public function setConnectionOptions($connectionOptions) {
$this->connectionOptions = $connectionOptions;
}
public function getProxyLibrary() {
return $this->proxyLibrary;
}
public function setProxyLibrary($proxyLibrary) {
$this->proxyLibrary = $proxyLibrary;
}
public function getProxyNamespace() {
return $this->proxyNamespace;
}
public function setProxyNamespace($proxyNamespace) {
$this->proxyNamespace = $proxyNamespace;
}
public function getCache() {
return $this->cache;
}
public function setCache($cache) {
$this->cache = $cache;
}
public function getEntityLibrary() {
return $this->entityLibrary;
}
public function setEntityLibrary($entityLibrary) {
$this->entityLibrary = $entityLibrary;
}
public function getApplicationMode() {
return $this->applicationMode;
}
public function setApplicationMode($applicationMode) {
$this->applicationMode = $applicationMode;
}
public function getEntityManager() {
return $this->entityManager;
}
public function setEntityManager($entityManager) {
$this->entityManager = $entityManager;
}
/** * Bootstrap Doctrine, setting the libraries and namespaces and creating * the entitymanager */
public function bootstrap() {
$this->registerClassLoader(); // Load cache
if ($this->getApplicationMode() == self::APP_MODE_DEVELOPMENT) {
$this->cache = new ArrayCache;
} else {
$this->cache = new ApcCache;
} /** #var $config Doctrine\ORM\Configuration */ $config = new Configuration;
$config->setMetadataCacheImpl($this->cache);
$driverImpl = $config->newDefaultAnnotationDriver($this->getEntityLibrary());
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($this->cache);
$config->setProxyDir($this->getProxyLibrary());
$config->setProxyNamespace($this->getProxyNamespace());
if ($this->applicationMode == self::APP_MODE_DEVELOPMENT) {
$config->setAutoGenerateProxyClasses(true);
} else {
$config->setAutoGenerateProxyClasses(false);
} $this->entityManager = EntityManager::create($this->getConnectionOptions(), $config);
}
/** * Register the different classloaders for each type. */
private function registerClassLoader() { // Autoloader for all the Doctrine library files
//Doctrine was done by public_html/libraries/doctrine/vendor/autoload.php
// $classLoader = new ClassLoader('Doctrine', dirname(__FILE__) . '/');
// $classLoader->register(); // Autoloader for all Entities
//name of ComposerAutoloader is defined in /public_html/libraries/doctrine/vendor/composer/autoload_real.php
$modelLoader = ComposerAutoloaderInit825f56ea1383e6b7fef7ea99c51fea36::getLoader();
$modelLoader->set("Entities\\",dirname(__FILE__)."/../../components/com_"
//not sure how to do the proxies yet, have to check this with production settings
// $proxiesClassLoader = new ClassLoader('Proxies', $this->getProxyLibrary());
// $proxiesClassLoader->register();
}
}
?>
The Joomla model save function looks something like this (checking received JSON should be done in a controller or helper function):
public function save() {
//a textbox having the name 'json' or xhr post
$link = JRequest::getVar('json',false,'post');
if($link==false){
return;
}
$link = json_decode($link);
$newLink = new Link();
$newLink->setId($link->id);
$newLink->setName($link->name);
foreach($link->categories as $category){
$cat = new Category();
$cat->setId($category->id);
$cat->setName($category->name);
$newLink->addCategorie($cat);
}
$this->em->persist($newLink);
$this->em->flush();
return $link;
}
I guess the code as is will break when using APP_MODE_PRODUCTION in /public_html/components/com_bugs/bugs.php

Resources