Laravel: Change base URL? - laravel

When I use secure_url() or asset(), it links to my site's domain without "www", i.e. "example.com".
How can I change it to link to "www.example.com"?

First change your application URL in the file config/app.php (or the APP_URL value of your .env file):
'url' => 'http://www.example.com',
Then, make the URL generator use it. Add thoses lines of code to the file app/Providers/AppServiceProvider.php in the boot method:
\URL::forceRootUrl(\Config::get('app.url'));
// And this if you wanna handle https URL scheme
// It's not usefull for http://www.example.com, it's just to make it more independant from the constant value
if (\Str::contains(\Config::get('app.url'), 'https://')) {
\URL::forceScheme('https');
//use \URL:forceSchema('https') if you use laravel < 5.4
}
That's all folks.

.env file change in
APP_URL='http://www.example.com'
config/app.php :
'url' => env('APP_URL', 'http://www.example.com')
In controller or View call with config method
$url = config('app.url');
print_r($url);

Related

Cannot get value from config in Lumen

I want to change the timezone in lumen, but I cannot get the value from config, it always give the default value UTC.
I've tried everything I know, to the point changing the default value to what I wanted. But still the timezone wont change
AppServiceProvider
public function register()
{
//set local timezone
date_default_timezone_set(config('app.timezone'));
//set local date name
setLocale(LC_TIME, $this->app->getLocale());
URL::forceRootUrl(Config::get('app.url'));
}
Bootstrap.app
(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
dirname(__DIR__)
))->bootstrap();
date_default_timezone_set(env('APP_TIMEZONE', 'Asia/Jakarta'));
$app->configure('app');
Config.app
'timezone' => env("APP_TIMEZONE", "Asia/Jakarta"),
.env
APP_TIMEZONE="Asia/Jakarta"
APP_LOCALE="id"
Also if I make a variable inside config.app such as:
'tes_var' => 'Test'
And using it like this:
\Log::info(config('app.tes_var'));
The result in Log is null, I can't get the value from tes_var.
I don't have any idea what's wrong here, if it's in Laravel maybe this is happened because cached config, but there's no cached config in Lumen. Maybe I miss some configuration here?
Thanks
First, you should create the config/ directory in your project root folder.
Then create a new file app.php under the config directory i.e. config/app.php
Now add whatever config values you want to access later in your application in the config/app.php file.
So, instead of creating a config.php file you should make a config directory and can create multiple config files under the config directory.
So final code will be like this:
config/app.php will have:
<?PHP
return [
'test_var' => 'Test'
];
Can access it anywhere like this:
config('app.tes_var');
Although Lumen bootstrap/app.php has already loaded the app.php config file (can check here: https://github.com/laravel/lumen/blob/9.x/bootstrap/app.php)
If not loaded in your case, you can add the below line in bootstrap/app.php file:
$app->configure('app');
Hope it will help you.
In order to use the env file while caching the configs, you need to create a env.php inside the config folder. Then, load all env variables and read as "env.VARIABLE_FROM_ENV". Example env.php:
<?php
use Dotenv\Dotenv;
$envVariables = [];
$loaded = Dotenv::createArrayBacked(base_path())->load();
foreach ($loaded as $key => $value) {
$envVariables[$key] = $value;
}
return $envVariables;
then read in your code:
$value = config('env.VARIABLE_FROM_ENV', 'DEFAULT_VALUE_IF_YOU_WANT');

Laravel Route Controller issue

I am trying to add a new route to my application and can't seem to get it to work. I keep getting a 404 error. It looks like the physical path is looking at the wrong directory. Currently looking at D:\Web\FormMapper\blog\public\forms but should be looking at D:\Web\FormMapper\blog\resources\view\layout\pages\forms.blade.php
My request URL:
http://localhost/FormMapper/ /works fine
http://localhost/FormMapper/forms /doesn't work
http://localhost/FormMapper/forms.php /No input file specified.
my FormsController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormsController extends Controller
{
public function index()
{
return view('layouts.pages.forms');
}
}
My web.php:
Route::get('/', function () {
return view('layouts/pages/login');
});
Route::get('/forms', 'FormsController#index');
My folder structure looks like this:
My config/view.php
return [
'paths' => [
resource_path('views'),
],
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];
you must use dot for this. In your controller change to this:
return view('layouts.pages.forms');
If your route only needs to return a view, you may use the Route::view method. Like the redirect method, this method provides a simple shortcut so that you do not have to define a full route or controller. The view method accepts a URI as its first argument and a view name as its second argument. In addition, you may provide an array of data to pass to the view as an optional third argument:
Route::view('/', 'layouts.pages.login');
Route::view('/forms', 'layouts.pages.forms', ['foo' => 'bar']);
Check docs
After tracking digging deeper I determined that the issue was that IIS requires URL rewrite rules in place for Laravel to work properly. The index.php and '/' route would work b/c it was the default page but any other pages wouldn't. To test this I used the
php artisan serve
approach to it. and everything worked properly. Unfortunately I am unable to do this in production so I needed to get it to work with IIS.

Laravel PUT routes return 404

I'm trying to update data in the database
but it returns error 404 not found in postman
Route::put('/products/{id}','productController#update');
Just add 'Accept: application/json' header to request.
Please provide more code so we can find exactly where your problem is.
I assume you wrote the route in the api.php file and not in web.php file.
If you do so, you must enter the route as api/products/1.
You have to be aware of the route group prefix as well if you are using it. Every routes inside a group prefix will be wrapped and requires the prefix string in the beginning every time you want to access it.
For instance:
in web.php file:
Route::group(['prefix' => 'api'], function () {
Route::put('products/{id}', 'productController#update');
});
# this will require you to access the url by tyiping "api/products/1".
and in the api php file (this is the more likely for new users have to be aware):
Route::group(['prefix' => 'api'], function () {
Route::put('products/{id}', 'productController#update');
});
# this will require you to access the url by tyiping "api/api/products/1" since the api.php file will automatically wrap your routes within an api prefix.
and one more thing you need to know, if you are using a getRoutesKeyName method on your model, you should follow wether the wildcard to use id's or maybe slug based on what you type inside the method.
For instance:
public function getRoutesKeyName(){
return 'slug';
}
# this will require you to type "products/name-of-product" instead of "products/1"

Dynamic route url change is not reflecting in laravel package

I am creating a package which gives a config file to customize the route url which it will add, I can see config file values in the controller, but same config('app_settings.url') is coming as null in
pakacge/src/routes/web.php
Route::get(config('app_settings.url'), 'SomeController')
my tests are also giving 404 and app_settings config change is not getting picked by route.
function it_can_change_route_url_by_config() {
// this should be default url
$this->get('settings')
->assertStatus(200);
// change the route url
config()->set('app_settings.url', '/app_settings');
$this->get('app_settings')
->assertStatus(200);
$this->get('settings')
->assertStatus(400);
}
app_setting.php
return [
'url' => 'settings',
'middleware' => []
];
It works when I use this package, but tests fail.
Please help How I can give the option to change the route url from config.
To be honest I think it's impossible to make such test. I've tried using some "hacky" solutions but also failed.
The problem is, when you start such test, all routes are already loaded, so changing value in config doesn't affect current routes.
EDIT
As alternative solution, to make it a bit testable, in config I would use:
<?php
return [
'url' => env('APP_SETTING_URL', 'settings'),
'middleware' => []
];
Then in phpunit.xml you can set:
<env name="APP_SETTING_URL" value="dummy-url"/>
As you see I set here completely dummy url to make sure this custom url will be later used and then test could look like this:
/** #test */
function it_works_fine_with_custom_url()
{
$this->get('dummy-url')
->assertStatus(200);
$this->get('settings')
->assertStatus(404);
}
Probably it doesn't test everything but it's hard to believe that someone would use dummy-url in routing, and using custom env in phpunit.xml give you some sort of confidence only custom url is working fine;

Laravel passing all routes for a particular domain to a controller

Working on a Laravel 4.2 project. What I am trying to accomplish is pass every URI pattern to a controller that I can then go to the database and see if I need to redirect this URL (I know I can do this simple in PHP and do not need to go through Laravel, but just trying to use this as a learning experience.)
So what I have at the moment is this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('?', 'RedirectController#index');
});
I am routing any subdomain which I deem as a "redirect subdomain" ... The ? is where I am having the problem. From what I have read you should be able to use "*" for anything but that does not seem to be working. Anyone have a clue how to pass any URL to a controller?
And on top of that I would ideally like to pass the FULL URL so i can easily just check the DB and redirect so:
$url = URL::full();
Try this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('{path}', 'RedirectController#index')
->where('path', '.*');
});
And your controller will reseive the path as first argument
public function index($path){
// ...
}
In case you're wondering, the where is needed because without it {path} will only match the path until the first /. This way all characters, even /, are allowed as route parameter

Resources