How to use traits in Laravel models? - php

Hello i'm laravel beginner
I want to make trait and use it in my model but at run time i got error that the trait is not found
my trait :
namespace App;
use Illuminate\Support\Facades\Schema;
trait GeneralModel
{
public static function testStaticFunction()
{
dd('test');
}
}
my model :
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use GeneralModel;
}
my controller
namespace App\Http\Controllers;
use App\Comment;
class SearchController extends Controller
{
public function find()
{
Comment::testStaticFunction();
}
}
error received
Trait 'App\GeneralModel' not found

In composer.json add this:
"autoload" : {
"classmap": [
"database/seeds",
"database/factories"
],
"files" : [
"app/GeneralModel.php" // <----------- ADD THIS
],
"psr-4" : {
"App\\": "app/"
}},
Then run composer dump-autoload

Please check the GeneralModel.php in app folder. And execute the below command in your project root path.
php artisan dump-autoload

You Have to Use
Composer dump-autoload
In Your command line
hope it's help

Related

How to fix Class 'app\hotelroom' not found error in laravel?

Im new to laravel , i have created migration and the table (hotelroom) earlier but forgot to create the model for the same ,bu now after creating the model and trying to retrieve the data , im getting above error
This is where it highlights the error
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\hotelroom;
class manage_roomscontroller extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$arr['hotelrooms']=hotelroom::all();
return view('admin.rooms.index')->with($arr);
}
}
Arguments
"Class 'app\hotelroom' not found"
``````````````````````````````````
model ( located under app directory)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class hotelroom extends Model
{
}
can someone tell me where the issue is? is it because i have created the model later ?( not at the same time while I created the migration). or its some other issue?
This error is because of app which will not work, you need to put proper namespace name as like below
use App\hotelroom;
The app directory is namespaced under App by default. You can open composer.json file and see that the app directory is set up for psr-4 autoloading:
"psr-4": {
"App\\": "app/"
},

Reflection Exception : Class ClassName doesn't exist

I am using Laravel 5.5. I have added a custom directory inside App folder in my workspace. So, the folder structure is:
Inside App\Bishwa\Transformers there are two PHP files:
Transformer.php
LessonTransformer.php
Those files look like follows:
Transformer.php
<?php
namespace Bishwa;
abstract class Transformer {
public function transformCollection(array $items){
return array_map([$this, 'transform'], $items);
}
public abstract function transform($item);
}
LessonTransformer.php
<?php
namespace Bishwa;
class LessonTransformer extends Transformer {
public function transform($lesson){
return [
'title' => $lesson['title'],
'body' => $lesson['body'],
'active' => (boolean)$lesson['some_bool']
];
}
}
Then Inside LessonsController.php I have the following:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Lesson;
use Bishwa\LessonTransformer;
class LessonsController extends Controller
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer){
dd('ok');
}
While running action of the controller, It gave me an error message saying:
Reflection Exception: Class Bishwa\LessonTransformer does not exist
I have tried composer dump-autoload, restarting the server again but none of them helped. Am I doing wrong while Namespacing or What?
Change your namespace of the files in your custom directory to App\Bishwa.
Well thanks to Jerodev and Jack. Since, both of them were write I decided to write myself a combined solution to this problem.
1st Solution:
In case of custom namespaces and custom classes I have to include the path to classname in Composer.json file in the following portion:
"autoload": {
"classmap": [
"database/seeds",
"database/factories",
"app/Bishwa/Transformers"
],
"psr-4": {
"App\\": "app/"
}
2nd Solution:
Changing NameSpace of my files to custom directory App\Bishwa .
Namespace of transformer.php and LessonTransformer.php now becomes:
namespace App\Bishwa\Transformers;
While using in LessonsController:
use App\Bishwa\Transformers\LessonTransformer;
Once again, big thanks to Jerodev and Jack. Its my silly mistake, that I couldn't figure that out.

How to keep seeder files separate and clean in laravel?

I want to keep my seeder files separate. for example UsersTableSeeder.php , PostsTableSeeder.php and then call them in main seeder file (DatabaseSeeder.php) :
Example:
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(PostsTableSeeder::class);
}
}
usersTableSeeder.php :
<?php namespace App\Seeds;
use Illuminate\Database\Seeder;
use App\User;
class UserTableSeeder extends Seeder {
public function run()
{
//DB::table('users')->delete();
// user1
User::create(array(
'name' => 'ahmad',
'email' => 'ahmad#ahmad.com',
'password' => 'ahmad'
));
}
}
my UsersTableSeeder.php and PostsTableSeeder.php files are in the same
directory that DatabaseSeeder.php is.
should I use psr-4 autoloading ? how?
Composer.json configuration
composer.json has a autoload key to configure additional autoload paths.
You can give it a try:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
}
Example from my composer.json
Remove the namespace line from your seeder classes. They are found by the classmap entries now.
Explicit namespaces
OR
Keep the namespaces and add them in calls to ->call().
Wherever you write a classname you can fully qualify the class with its namespace (should be \database\seeds\YourClass::class, which can depend on your composer.json settings), or add a use statement at the beginning of the file.
You may have to run composer dump-autoload. It worked for me.
As a side note, it'd be cleaner to use PSR-4 for seeds and migrations (tests already do).

Custom helper: class not found. Laravel 5.1

I've created a custom new file, app/Http/Helpers.php and added:
<?php
namespace app\Http;
class ConnectionsHelper {
public static function organisation($id) {
return 'ID:'.$id;
}
}
In Composer.json, in the autoload-block I've added:
"files": [
"app/Http/Helpers.php"
]
And then I ran "composer dump-autoload".
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class myController extends Controller
{
public function index()
{
echo ConnectionsHelper::organisation(2);
}
}
And get in return:
FatalErrorException in OrganisationsController.php:
Class 'App\Http\Controllers\ConnectionsHelper' not found
You need to provide a namespace alias in your controller.
use App\Http\ConnectionsHelper
Autoloading a file does not mean that the classes in that file are required/included in all other scripts in the app. It just means that you are making those files available to your app. In this case, your helper file is already inside the App namespace which is autoloaded by default, so you can remove the files bit of your composer.json completely.

ReflectionException - Class DatabaseSeeder does not exist , Laravel Seeder [duplicate]

This question already has answers here:
Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist
(14 answers)
Closed 1 year ago.
I have database seeder clases in diferent folder. When i write db:seed the console shows this error:
[ReflectionException] Class DatabaseSeeder does not exist , Laravel Seeder
One class is this:
namespace Database\Seeds;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use TiposCompromisosTableSeeder;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call('TiposCompromisosTableSeeder');
}
}
and my other class is
namespace Database\Seeds;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class TiposCompromisosTableSeeder extends Seeder{
public function run(){
DB::table('tipos')->insert(array(
'nombre' => 'prioridad',
'tabla' => 'compromisos',
'str1' => 'baja',
'int1' => 1
));
}
}
I've tried to use
composer dump-autoupload
but doesn't work.
As you can see, I have both clases in the same namespace.
Help please.
If you've recently upgraded your Laravel version, check your composer.json
Your "autoload" section should look something like the snippet below
NOTE: you may have to add the "database" entry under the "classmap"
"autoload": {
"classmap": [
"app/Library",
"app/Models",
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Library/helpers.php"
]
},
You should then run composer dump-autoload and try php artisan db:seed
remove your namespace definition in two classes, and use "composer dump-autoload".
Then it will works fine.
You should add this line into composer.json file inside "psr-4":
"Database\\Seeders\\": "database/seeders/"
it means that should be something like:
"autoload": {
"psr-4": {
"App\\": "app/",
"Modules\\": "Modules/",
"Database\\Seeders\\": "database/seeders/"
}
},
Just put it all in the DatabaseSeeder.php file like this:
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
$this->call('TiposCompromisosTableSeeder');
}
}
class TiposCompromisosTableSeeder extends Seeder{
public function run(){
DB::table('tipos')->insert(array(
'nombre' => 'prioridad',
'tabla' => 'compromisos',
'str1' => 'baja',
'int1' => 1
));
}
}
There is a need it only one change, rename the folder seed to seeders.
Solved: by adding
namespace database\seeds;
and then running command:
composer dump-autoload --no-dev
Also make sure database folder exist inside your project. If you accidently delete the database folder and run migration command. You will get this error too.
Does adding the --no-dev flag help?
composer dump-autoload --no-dev
source

Categories