I am new to namespaces. Using laravel.
my folder structure is
app
-lib
-Services
-Users
-UserCreator.php
-controllers
-SiteController.php
composer.json
My problem is it says Class Services/Users/UserCreator does not exist everytime I try and load it.
UserCreator.php:
<?php
namespace Services\Users;
class UserCreator {
}
SiteController.php
<?php
use Services\Users\UserCreator;
// more code here...
if ($validator->fails()) {
echo 'fail';
} else {
$userCreator = App::make('Services/Users/UserCreator');
if ($userCreator::create(Input::all())) {
return Redirect::to('/')->with('message', 'Account Created');
} else {
return Redirect::to('/error');
}
}
}
Composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
],
"psr-4": {
"Services\\Users\\": "app/lib/Services/Users/UserCreator"
}
}
I only included what I thought you would need. Let me know if you need anything else. Thanks!
In your composer.json change psr-4 section to this
"psr-4": {
"Services\\": "app/lib/Services"
}
Also change
$userCreator = App::make('Services/Users/UserCreator');
to
$userCreator = App::make('Services\Users\UserCreator');
^ ^
Related
I have a json request with household_data. I have tried to use validator on family_no which is a unique field. the json I'm working on is :
[
{
"BasicInfo": {
"ward": "12",
"tole_name": "Sahayogi Nagar",
"house_no": "21",
"family_no": "420",
"district": "Lalitpur",
},
"Family": [
{
"caste": "bahun",
"religion": "hindu",
}
]
}]
But the validator fails always, even if the family_no is unique or not and returns:
{
"family_no": [
"The family no field is required."
]
}
here is my controller code:
$items = json_decode($request->household_data);
// return json_decode($request->household_data);
if($request->household_data){
$validator = Validator::make($items, [
'family_no' => 'required|unique:households|max:255',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 404);
}
else{
foreach($items as $key=>$item){
$householdId = $this->saveHousehold($item);
return $householdId;
}
}
}
Anyone could please help me validate the unique field family_no?
checkout array validator of laravel on the doc webiste https://laravel.com/docs/7.x/validation#validating-arrays. But for your validation you have to write it like this :
{
"BasicInfo.family_no": [
"The family no field is required."
]
}
I want to use a helper functions but I got this error in my view :
Call to undefined function createSubCategories()
path of my helper functions:
Http\Controllers\Utilities\Helpers.php
my hlper :
<?php
namespace App\Http\Controllers\Utilities;
function createSubCategories($parent_cat_id = 0)
{
$subs = DB::table('categories')->where('parent_cat_id', '=', $parent_cat_id)->get();
if (count($subs) > 0) {
echo '<ul>';
foreach ($subs as $sub) {
echo '<li>' . $sub->title_fa;
echo $this->createSubCategories(($sub->id));
echo '</li>';
}
echo '</ul>';
}
}
in composer.json :
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files":
[
"app/Http/Controllers/Utilities/Helpers.php"
]
},
I used composer dump-autoload.
my view:
{{createSubCategories(0)}}
solved:
I just removed the namespace :
namespace App\Http\Controllers\Utilities;
I could reproduce your problem and the solution is to leave out the line
namespace App\Http\Controllers\Utilities;
in your Helpers.php
I have faced same problem that you have mentioned above. in my composer.json, I did not integrate the helper functions. By integrating in composer.json->autoload->files, now it is ok.
"autoload": {
"files":[
"app/Helper/setting.php"
]
}
if your path is alright then it will be ok. For Every change of your helper function you must run the command composer dump-autoload.
im trying to use Auth::attempt($credentials) in my controller and here is my sample code
$credentials= [
'SystemUserName' => Input::get('username'),
'SystemUserPassword' => Input::get('password')
];
then im having a error saying Undefined Index: Password only to know that i can use any field for username but i can't do that for the password because it should be 'password'. the thing is SystemUserName and SystemUserPassword are column names in my database. How can i do this properly? any ideas?
Unfortunately you can use only the 'password' column name with the included database and eloquent drivers, because the column name is hardcoded in the user provider. So your only bet is to create your own custom driver by extending the Eloquent one. This can be done in four easy steps as explained below:
1. Create your custom driver class file in app/extensions/CustomUserProvider.php file with the following contents:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Auth\UserProviderInterface;
class MyCustomUserProvider extends EloquentUserProvider implements UserProviderInterface {
public function retrieveByCredentials(array $credentials)
{
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if ($key != 'SystemUserPassword') $query->where($key, $value);
}
return $query->first();
}
public function validateCredentials(UserInterface $user, array $credentials)
{
return $this->hasher->check($credentials['SystemUserPassword'], $user->SystemUserPassword);
}
}
2. Add "app/extensions" to your composer.json in the classmap section:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/extensions" // <-- add this line here
]
},
Then run a php composer dump-autoload.
3. In your app/start/global.php file add this to register your custom driver:
Auth::extend('mydriver', function($app)
{
return new MyCustomUserProvider($app['hash'], Config::get('auth.model'));
});
4. Then just set the driver in your app/config/auth.php to this:
'driver' => 'mydriver',
This was tested and it works just fine.
Mind you, this will work assuming your user passwords were hashed with the Hash::make() method Laravel offers and stored that way in the database. If not, then you need to adjust the validateCredentials method in MyCustomUserProvider with your own compare method between the plain and hashed password.
I have the following directory structure
app
| ...
| lib
| | Macro.php
| | Events.php
| ...
In my composer.json I have
"autoload": {
"classmap": {
...
"app/lib"
...
}
}
Events.php loads fine and updates the DB when the event triggers:
<?php
Event::listen('auth.login', function($user) {
$user->last_login = new DateTime;
$user->save();
});
Macros.php will always return the error Method messageBox does not exist if the macro is used in a view:
<?php
Form::macro('test', function()
{
return 'test';
});
I have run composer dump-autoload. Why is the Macros.php not autoloading?
The autoload classmap section in composer.json maps excatly that: classes. So it won't help you in this instance, because you don't have a class declaration in that file. You can however autoload files as well with composer, by adding this to the autoload section:
"autoload": {
"classmap": [
...
],
"files": [
"app/lib/Macros.php"
]
}
As an alternative you could always manually include the file in Laravel's app/start/global.php like so:
require app_path() . '/lib/Macros.php';
How can I autoload helper functions (outside of any class)? Can I specify in composer.json some kind of bootstrap file that should be loaded first?
You can autoload specific files by editing your composer.json file like this:
"autoload": {
"files": ["src/helpers.php"]
}
(thanks Kint)
After some tests, I have came to the conclusions that adding a namespace to a file that contains functions, and setting up composer to autoload this file seems to not load this function across all the files that require the autoload path.
To synthesize, this will autoload your function everywhere:
composer.json
"autoload": {
"files": [
"src/greetings.php"
]
}
src/greetings.php
<?php
if( ! function_exists('greetings') ) {
function greetings(string $firstname): string {
return "Howdy $firstname!";
}
}
?>
...
But this will not load your function in every require of autoload:
composer.json
"autoload": {
"files": [
"src/greetings.php"
]
}
src/greetings.php
<?php
namespace You;
if( ! function_exists('greetings') ) {
function greetings(string $firstname): string {
return "Howdy $firstname!";
}
}
?>
And you would call your function using use function ...; like following:
example/example-1.php
<?php
require( __DIR__ . '/../vendor/autoload.php' );
use function You\greetings;
greetings('Mark'); // "Howdy Mark!"
?>