Following this topic Use a custom function everywhere in the website I need a bit of help to finish what has been started.
So I created a folder in the app folder: Customs
Then I created a helpers.php file that has the following code:
<?php
use Illuminate\Support\Str;
if (! function_exists('str_slug')) {
/**
* Generate a URL friendly "slug" from a given string.
*
* #param string $title
* #param string $separator
* #return string
*/
function my_slug($title, $separator = '-')
{
$title = str_replace('\'','_',$title);
return Str::slug($title, $separator);
}
}
I read that I now have to update my composer.json, and especially the autoload section which is basically:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
I don't understand what I should do now... psr-4 already says that the whole app folder is autoloaded, no?
I also tried to put the full path to the helpers.php but it did not work either.
What am I doing wrong?
Your autoload should have something like that:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/helpers.php"
]
},
where files are your custom files. Also as is mentioned in Use a custom function everywhere in the website question I advice you to use traits for e.g. trait StringSluggify. It keeps OOP way.
Create a folder inside of app/ called Helpers.
Inside of app/Helpers create your custom class
namespace App\Helpers;
class FooHelper{
public static function bar(){
return 'bar';
}
}
Run composer dump-autoload to update autoload.
Here you are now able to use your helper functions like:
$bar = \App\Helper\FooHelper::bar();
If your plan is attach a facade, then edit facades array in config/app.php like so:
'Foo' => \App\Helpers\FooHelper::class
Now you can call your functions like:
public function controllerFunction(){
$bar = \Foo::bar();
}
use it in your view {{my_slug($collection->value)}} or in your controllers with the namespacing App\customs\my_slug($value) or by adding use \App\customs to the top of your controller and then my_slug($value)
Related
I am upgrading a legacy laravel application from Laravel 5 to 8 and ran into a brick wall. None of my service providers work, and I cannot figure out why.
Previous Structure
app
-->Services
------>Stripe
Within each service provider folder, I'd create three files like so:
Stripe.php
StripeFacade.php
StripeServiceProvider.php
within stripe.php
<?php
namespace app\Services\Stripe;
class Stripe
{
}
?>
within StripeFacade.php
<?php
namespace app\Services\Stripe;
use Illuminate\Support\Facades\Facade;
class StripeFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Stripe';
}
}
within StripeServiceProvider.php
<?php
namespace app\Services\Stripe;
use Illuminate\Support\ServiceProvider;
class StripeServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton('Stripe', function($app) {
return new Stripe();
});
}
}
in my Config/app.php file, I'd register the service provider and facade like so:
'providers' => [
app\Services\Stripe\StripeServiceProvider::class,
],
'aliases' => [
'Stripe' => app\Services\Stripe\StripeFacade::class,
]
In my controller, I'd call the Stripe service as
use Stripe;
...
public function example(){
$auth = Stripe::auth();
}
Then I'd get this error in the Config/app.php file
Class "app\Services\Stripe\StripeServiceProvider" not found
I tried adding the Services directory to my psr-4 and didn't seem to get any luck, even after dumping configs and autoload.
"autoload": {
"psr-4": {
"App\\": "app/",
"Services\\": "app/Services",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
any help? :)
In your comment, you posted an error:
Class App\Services\Stripe\StripeServiceProvider located in ./app/Services /Stripe/StripeServiceProvider.php does not comply with psr-4 autoloading standard. Skipping.
I noticed an extra space in ./app/Services /Stripe.
Perhaps you have created the Services / directory with a space at the end.
Some improvements are to rename app\ to App\ and remove the "Services\\": line from your composer.json. Run composer dump-autoload after these changes.
Use the below code
namespace App\Services\Stripe;
use App\Services\Stripe\StripeServiceProvider::class
Hi I am new to creating factories on Laravel and I am setting up a blog website. There is no need for users at this time as it is a draft but I am trying to set up a factory to create dummy blog posts.
I have a Post.php file which looks like this:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
}
My PostFactory looks like this
use App\Post;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(App\Post::class, function (Faker $faker) {
return [
'title' => $faker->name,
'body' => $faker->unique()->safeEmail,
];
});
but everytime i try to create the records it throws this error "InvalidArgumentException with message 'Unable to locate factory for [App/Post].'"
i know its about linking these files but i cannot figure out how to do it.
First as mentioned above your file must be named Post.php and not posts.php.
Since you are using App\Post at the beginning of your file, you can simply call Post::class
$factory->define(Post::class, function (Faker $faker)
Another option could also be that you are missing the factories folder in your composer classmap:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
},
If this does not solve the problem, then you might need to post your code where you are calling your factory
#edit
this is pretty good overview over conventions
I have two laravel projects on the same server connected to the same database on the Cpanel, the first project is the main project and the other one is a subdomain project.
I want to view images for the subdomain project from the images folder in the main project.
I tried to return back to the directory but it didn't work
<img src="{{ url('../images/'.$item->image)}}">
however, when I store images from the subdomain project to the images folder in the main project, it works well. but I can't retrieve them back to the view.
Ok - so here's what you could do to make it work.
If you don't have already, create your own helpers file and add it to composer's autoload:
app/helpers.php
<?php
if (! function_exists('parentAsset')) {
/**
* Generate a parentAsset path for the application.
*
* #param string $path
* #param bool|null $secure
* #return string
*/
function parentAsset($path, $secure = null)
{
return app('parentUrl')->asset($path, $secure);
}
}
composer.json
{
//...
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
],
"files": [
"app/helpers.php"
]
},
//...
}
Register parentUrl in the container
app/Providers/AppServiceProvider.php
use Illuminate\Routing\UrlGenerator;
public function register()
{
$this->app->singleton('parentUrl', function ($app) {
$routes = $app['router']->getRoutes();
$app->instance('routes', $routes);
return new UrlGenerator(
$routes,
$app->rebinding('request', $this->requestRebinder()),
$app['config']['app.parent_asset_url']
);
});
}
/**
* Get the URL generator request rebinder.
*
* #return \Closure
*/
protected function requestRebinder()
{
return function ($app, $request) {
$app['url']->setRequest($request);
};
}
Please note the new config entry for app namespace: parent_asset_url. You now need to add it to your app.php config file.
config/app.php
[
//...
'asset_url' => env('ASSET_URL', null),
'parent_asset_url' => env('PARENT_ASSET_URL', null),
//...
]
Lastly you need to add PARENT_ASSET_URL variable to your .env file and specify the url of your parent application.
PARENT_ASSET_URL=https://google.com
Recompile autoloader
composer dump-autoload -o
And you can now use the parentAsset helper to load files directly from the parent domain:
<img src="{{ parentAsset('/assets/images/logo.svg') }}">
Hope this helps.
I have created app/Http/helpers.php
if (!function_exists('getLocation')) {
function getLocation($request)
{
return 'test';
}
I have added files section in composer.json autoload
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Http/helpers.php"
]
},
Here is my controller :
namespace App\Http\Controllers;
use App\Jobs\ChangeLocale;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Log;
class HomeController extends Controller
{
public function index(Request $request)
{
$data['location'] = getLocation($request);
}
}
When I call the function in controller as getLocation($request); it is saying "Call to undefined function App\Http\Controllers\getLocation()"
This is working fine in my local , but not on remote server. What am I missing in my remote server. Tried composer install and composer dump-autoload.
UPDATE:
The helper file is not getting listed in vendor/composer/autoload_files.php
On server, you need to execute:
composer dumpautoload
because it is not found on vendor/autoload.php
Try like this,
create Helpers directory inside the app directory.
create a Example.php file inside the Helpers directory
create a alieas for this file at config/app.php file
Ex: 'Example' => App\Helpers\Example::class,
The code in the Example.php like follows,
<?php
namespace App\Helpers;
class Example
{
static function exampleMethod()
{
return "I am helper";
}
}
Using the above Example helper in Controller files like follows,
<?php
namespace App\Http\Controllers;
use App\Helpers\Example;
class HomeController extends Controller
{
public function index(Request $request)
{
return Example::exampleMethod();
}
}
Using the above Example helper in blade view files like follows,
<div>{{ Example::exampleMethod()}}</div>
This will help you to get solution.
Make Sure the structure of the Helper.php is correct...
<?php
//no namespace, no classes
//classes are not helpers
if ( !function_exists('nextStage') ) {
function nextStage($currentStage) {
//if you need to access a class, use complete namespace
return \App\Models\Stage::where('id',$currentStage)->first()->next_stage;
}
}
More help on Laracast found here
I moved my User Model from App\User to App\Models\Users, I followed the proper instruction, the same thing working properly on Windows OS, while facing error on Ubuntu 14.04
Whenever I try to Login(When submit information) it gives me error
FatalErrorException in
/var/www/html/sms/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php
line 126: Class '\App\User' not found
I also run composer dump-autoload command, but no luck.
Also tried this
https://stackoverflow.com/a/28516582/1216451
Here is my settings for Models directory
composer.json
"autoload": {
"classmap": [
"database",
"app/Models"
],
"psr-4": {
"App\\": "app/"
}
},
Model Directory Structure
App/Models/
Model User.php
namespace App\Models;
Auth.php tried both lines, given below.
'model' => App\Models\User::class,
'model' => App\Models\User,
AuthController.php
use App\Models\User;
EloquentUserProvider.php path is sms/vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php line 126
public function createModel()
{
$class = '\\'.ltrim($this->model, '\\');
return new $class; //line# 126
}
Your configurations seems accurate, just reset them by using php artisan config:clear
Please check also all those files including relationship
the perfect way find out all, is to search folder excluding vendor.
config/services.php
config/auth.php
database\factories\Userfactory.php
public function user()
{
return $this->belongsTo(User::class);
}
Make sure that you have specified the correct namespace.
Like
App\Models\User
but this depend on youe file construction some time users but the Model User inside folder that named Models in older versions of laravel cus it's not there by default