I try to send some emails with a CLI command with php artisan of Laravel, something easy like :
php artisan invitation:send recipient#mail.com
This command is calling a UserController method which contains :
Mail::send('emails.beta.invitation', $data, function($message) use ($address)
{
$message->to($address)
->subject('My subject');
});
The problem is that when it creates the HTML using the view, all references to URL::asset('img/foo.png') in the template gives me a beautiful :
http://localhost/img/foo.png
instead of the website url :
http://mydomain.com/img/foo.png
If I call this method by calling it in the web browser, there is the good URI for the asset.
I even tried with an environment to the CLI but it doesn't work. (ie. --env=production)
Where am I wrong ?
All right, I got it.
When using the CLI, Laravel is using the config file app/config/app.php to read the 'url' (default 'url' => 'http://localhost').
So I just had to create a new config file under app/config/local/app.php with :
<?php
return array(
'url' => 'http://localhost:8000',
);
And to change the app/config/app.php with my production value :
'url' => 'http://mydomain.com'
Now it works well !
https://github.com/laravel/framework/issues/2554#issuecomment-246645265
mstephens commented on 13 Sep 2016
Hello
In App\Providers\RouteServiceProvider you can define the following:
/**
* #inheritdoc
*/
public function boot()
{
parent::boot();
/** #var \Illuminate\Routing\UrlGenerator $url */
$url = $this->app['url'];
// Force the application URL
$url->forceRootUrl(config('app.url'));
}
Related
I'm trying to write a test command in Laravel 9. In the below code the new user will create successfully But after creating need to redirect the Dashboard page
public function test_an_action_that_requires_authentication()
{
$user = $this->artisan('make:user',[
'name' => "username",
'email' => "useremail",
'password' => Str::random(8)
]);
}
How to redirect to the route after success created
We will use the assertExitCode method to assert that the command completed with a given exit code.
$this->artisan('module:import')
->expectsConfirmation('Do you really wish to run this command?', 'no')
->assertExitCode(1);
for more information you can find here
https://laravel.com/docs/9.x/console-tests
N.B. This code does not work in test. You can not redirect in an artisan command.
Said that, in laravel, to redirect to the home page, you can use this code in a controller function:
return redirect(url('/'));
I want to add to my Lumen project a daily Log.
I try this in the app.php (Folder Bootstrap/)
$logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
But this set me that error
Call to undefined method Monolog\logger::useDailyFiles()
Any help I appreciate...Thanks
If you look at the framework source code here you can see that it will not do daily logs, but rather write to a single log file lumen.log. There is a public method available configureMonologUsing seen here and referenced here that you can use to override the default behavior without extending the Application.
Lumen just sets a handler to monolog, so another good solution is you could do this:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
class LogServiceProvider extends ServiceProvider
{
/**
* Configure logging on boot.
*
* #return void
*/
public function boot()
{
$maxFiles = 5;
$handlers[] = (new RotatingFileHandler(storage_path("logs/lumen.log"), $maxFiles))
->setFormatter(new LineFormatter(null, null, true, true));
$this->app['log']->setHandlers($handlers);
}
/**
* Register the log service.
*
* #return void
*/
public function register()
{
// Log binding already registered in vendor/laravel/lumen-framework/src/Application.php.
}
}
Then don't forget to add the service provider to your Lumen bootstrap/app.php:
$app->register(\App\Providers\LogServiceProvider::class);
In Lumen 5.6 better way is to configure your default setting in .env as LOG_CHANNEL=daily
By default the setting is LOG_CHANNEL=stack which use single file for logging.
Starting from version 5.6, configuring the logging system is much easier:
Create directory config in your project if it doesn't exist
Copy the logging config file from
vendor/laravel/lumen-framework/config/logging.php to your project config dir
Edit file config/logging.php and adjust the channels property to your liking.
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
],
I am trying to implement this library for sending push notifications to iOS app. All my configurations are fine. When I tested the code snippet available at this page like this:
PushNotification::app('appNameIOS')
->to($deviceToken)
->send('Hello World, i`m a push message');
It threw this error:
Non-static method
Davibennun\LaravelPushNotification\PushNotification::Message() should
not be called statically
Rightly so, because when I opened the class, there was no such static method. There is one but that is not static. What am I doing wrong? Any help?
Edit 1
I have generated config file:
return array(
'hasalty_ios' => array(
'environment' =>'development',
'certificate' =>base_path('pem.p12'),
'passPhrase' =>'',
'service' =>'apns'
),
'hasalty_android' => array(
'environment' =>'production',
'apiKey' =>'yourAPIKey',
'service' =>'gcm'
)
);
Edit 2
My Laravel version is 5.5.31.
If you configure the library correctly, you should use
use Pushnotification;
instead of
use Davibennun\LaravelPushNotification\PushNotification;
When a user references any static method on the Cache facade, Laravel resolves the cache binding from the service container and runs the requested method (in this case, get) against that object.
How Facades Work
Edit
You must generate the config file before you use it:
php artisan vendor:publish --provider="Davibennun\LaravelPushNotification\LaravelPushNotificationServiceProvider" --tag="config"
Try to use this code:
Change here use Pushnotification instead
of use Davibennun\LaravelPushNotification\PushNotification;
I try to use the package Laravel\Socialite in my system in Lumen (5.1)
I added this in the config\services.php file :
<?php
//Socialite
'facebook' => [
'client_id' => '##################',
'client_secret' => '##################',
'redirect' => 'http://local.dev/admin/facebook/callback',
],
In bootstrap\app.php file :
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
Then I created a controller for the facebook authentication :
<?php
namespace App\Http\Controllers\Facebook;
use App\Http\Controllers\Controller;
use Laravel\Socialite\Contracts\Factory as Socialite;
class FacebookController extends Controller
{
public function redirectToProviderAdmin()
{
return Socialite::driver('facebook')->scopes(['manage_pages', 'publish_actions'])->redirect();
}
public function handleProviderCallbackAdmin()
{
$user = Socialite::driver('facebook')->user();
}
}
And in the routes.php :
$app->get('/admin/facebook/login', 'App\Http\Controllers\Facebook\FacebookController#redirectToProviderAdmin');
$app->get('/admin/facebook/callback', 'App\Http\Controllers\Facebook\FacebookController#handleProviderCallbackAdmin');
I just followed the documentation, changing according to my needs. When I go to page http://local.dev/admin/facebook/login, I get the following error :
Non-static method Laravel\Socialite\Contracts\Factory::driver() cannot be called statically, assuming $this from incompatible context
Indeed, according to the code, driver function must be instanciate.
EDIT : And if I try to instanciate this class, I get the following error :
Cannot instantiate interface Laravel\Socialite\Contracts\Factory
How do you make this module to work?
here's how that works in my case
in services.php file
'facebook' => [
'client_id' => '***************',
'client_secret' => '***************',
'redirect' => ""
],
i left redirect empty cause my site is multilingual (so, it fills in a bit later with sessions). if you use only one language, put there your callback absolute path. for example
"http://example.com:8000/my-callback/";
also check your config/app.php. in providers array
Laravel\Socialite\SocialiteServiceProvider::class,
in aliases array
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
my routes look like this
Route::get('facebook', 'Auth\AuthController#redirectToProvider');
Route::get('callback', 'Auth\AuthController#handleProviderCallback');
here's auth controllers methods. put in top
use Socialite;
//იობანი როტ
public function redirectToProvider(Request $request)
{
return Socialite::with('facebook')->redirect();
}
public function handleProviderCallback(Request $request)
{
//here you hadle input user data
$user = Socialite::with('facebook')->user();
}
my facebook app
giga.com:8000 is my localhost (so its the same localhost:8000)
as you can see in Valid OAuth redirect URI, you should put there your callback. in my case i use three urls cause i have three languages. in your case it should be just
http://your-domain-name.com:8000/callback
if you work on localhost, you should name your domain in config/services.php
mine look like this
'domain' => "your-domain.com",
after everything run these commands
php artisan cache:clear
php artisan view:clear
composer dump-autoload
restart your server, clear your browser cookies. hope it helps
I want to change the Laravel 5.1 storage path: something like /home/test/storage. This has the advantage that these files are not stored in the repository, which is fairly ugly I think.
In Laravel 4, this was very simple with bootstrap/paths.php.
In Laravel 5, it works by using $app->useStoragePath('/path/') in bootstrap/app.php. However, I want to define the storage path with a config option, like $app->useStoragePath(config('app.storage_path'). The config option calls an environment variable or returns a default location.
Doing this results in a Uncaught exception 'ReflectionException' with message 'Class config does not exist'; this makes sense, because this function is not loaded yet.
I tried setting the storage path just after booting:
$app->booted(function () use ($app) {
$app->useStoragePath(config('app.storage_root'));
});
This changed nothing. I also tried directly binding it to path.storage:
$app->bind('path.storage', function ($app) {
return config('app.storage_root');
});
The last option works partially; the view cache is now placed in the correct location, but the logs are still at the old location.
Set it up in .env
app.php
'app_storage' => env('APP_STORAGE', storage_path()),
app/Providers/AppServiceProvider.php
public function register()
{
$this->app->useStoragePath(config('app.app_storage'));
}
.env
APP_STORAGE=custom_location
Laravel 5.3 is in bootstrap/app.php
/*
|--------------------------------------------------------------------------
| Set Storage Path
|--------------------------------------------------------------------------
|
| This script allows us to override the default storage location used by
| the application. You may set the APP_STORAGE environment variable
| in your .env file, if not set the default location will be used
|
*/
$app->useStoragePath( env( 'APP_STORAGE', base_path() . '/storage' ) );
Here is a simple solution of changing the storage path in Laravel 5 like we do in Laravel 4
on bootstrap/app.php
# new storage path
# base_path() -> returns root path
$path_storage = base_path() . "../../storage";
# override already $app->storagePath using the function
$app->useStoragePath($path_storage);
this will make the storage path to be same with the session, views, cache, logs
This works on Laravel 5.2
File: app/Providers/AppServiceProvider.php
public function register() {
...
$this->app->useStoragePath(config('what_ever_you_want'));
...
}
Calling useStoragePath on your AppServiceProvider wouldn't do the job properly because the AppServiceProvider is called after the config files are loaded. so any use of storage_path in config files would still refer to the old storage path.
In order to properly solve this problem I suggest you extend Application class and then on the constructor of your own class write the followings.
/**
* MyApplication constructor.
*/
public function __construct($basePath = null)
{
parent::__construct($basePath);
// set the storage path
$this->afterLoadingEnvironment(function () {
$this->useStoragePath(/*path to your storage directory*/);
});
}
if your website is hosted;
move everything from public folder to root folder
$app->bind('path.public', function() {
return __DIR__;
});
add this code in your bootstrap/app.php :
$app->useStoragePath(__DIR__ . '/../custom-path/');
and in config/filesystem.php :
'local' => [
'driver' => 'local',
'root' => storage_path('everything'), //custom-path/everything
],
'public' => [
'driver' => 'local',
'root' => storage_path(''),
'url' => env('APP_URL'),
'visibility' => 'public',
],
and then run php artisan config:cache
This works on Laravel 5.8 because you have to load the environment variables before you try to use them.
File: bootstrap/app.php
$app->afterLoadingEnvironment(function() use ($app) {
$app->useStoragePath(env('APP_STORAGE', storage_path()));
});