Laravel Get Config Variable - laravel

In Laravel 5.0 I have set in config/app.php this:
return [
//...
'languages' => ['en','it'],
//...
]
Then, I have a blade wrapper in resources/views/frontend/includes/menus/guest.blade.php
#foreach (Config::get('languages') as $lang => $language)
But, Laravel says that foreach has no valid argument, which means that Config::get('languages') returns null.
I can't set custom variables in app.php?

You need to change it to:
#foreach (Config::get('app.languages') as $lang => $language).
Treat the first segment of your lookup as the files under /config, in this case app.php corresponds to Config::get('app.*')
If it wasn't obvious, you can use the helper function config() rather than Config::get() as well.

Laravel has a helper function for config which allows you to avoid instantiating a Config instance each time you access a value.
Simply use:
config('app.languages');

$languages = config('app.languages');
print_r($languages);
Get More Details with Placement Question Article

Related

Passing variable to .blade.php by return on Controller

I'm trying to pass a varible from the Controller to my .blade.php file.
I'm returning the view and compacted variables to the .blade.php but it doens't recognize the
variable.
This is the code of the Controller.
$contents = Storage::get($request->file('csv_file_1')->store('temporaryfiles'));
$contents2 = Storage::get($request->file('csv_file_2')->store('temporaryfiles'));
return view('comparison.comparison')->with(compact('contents'),$contents)->with(compact('contents2'),$contents2);
And i'm trying every way just to get an result but instead i'm getting the "Undefined variable $contents" page. The last method i used was a simple
<p>{{$contents}}</p>
I don't think it's correct but i don't really remember how to do it.
In controller return like:
return view('comparison.comparison', compact(['contents', 'contents2']);
And make sure your file is in resources/views/comparison/comparison.blade.php
Try this
$contents = Storage::get($request->file('csv_file_1')->store('temporaryfiles'));
$contents2 = Storage::get($request->file('csv_file_2')->store('temporaryfiles'));
return view('comparison.comparison', compact('contents','contents2'));
if you have defined a veriable above just use tha name inside compact as above and it can be acced inside blade as <p>{{$contents}}</p>
You can pass variables like that it's not mandatory to use compact.
return view('comparison.comparison', [
'contents' => $contents,
'contents2' => $contents2
]);
or if you want with compact:
return view('comparison.comparison')->with(compact('contents', 'contents1'));

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');

Get last part of current URL in Laravel 5 using Blade

How to get the last part of the current URL without the / sign, dynamically?
For example:
In www.news.com/foo/bar get bar.
In www.news.com/foo/bar/fun get fun.
Where to put the function or how to implement this in the current view?
Of course there is always the Laravel way:
request()->segment(count(request()->segments()))
You can use Laravel's helper function last. Like so:
last(request()->segments())
This is how I did it:
{{ collect(request()->segments())->last() }}
Use basename() along with Request::path().
basename(request()->path())
You should be able to call that from anywhere in your code since request() is a global helper function in Laravel and basename() is a standard PHP function which is also available globally.
The Route object is the source of the information you want. There are a few ways that you can get the information and most of them involve passing something to your view. I strongly suggest not doing the work within the blade as this is what controller actions are for.
Passing a value to the blade
The easiest way is to make the last part of the route a parameter and pass that value to the view.
// app/Http/routes.php
Route::get('/test/{uri_tail}', function ($uri_tail) {
return view('example')->with('uri_tail', $uri_tail);
});
// resources/views/example.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Avoiding route parameters requires a little more work.
// app/Http/routes.php
Route::get('/test/uri-tail', function (Illuminate\Http\Request $request) {
$route = $request->route();
$uri_path = $route->getPath();
$uri_parts = explode('/', $uri_path);
$uri_tail = end($uri_parts);
return view('example2')->with('uri_tail', $uri_tail);
});
// resources/views/example2.blade.php
The last part of the route URI is <b>{{ $uri_tail }}</b>.
Doing it all in the blade using the request helper.
// app/Http/routes.php
Route::get('/test/uri-tail', function () {
return view('example3');
});
// resources/views/example3.blade.php
The last part of the route URI is <b>{{ array_slice(explode('/', request()->route()->getPath()), -1, 1) }}</b>.
Try request()->segment($number) it should give you a segment of the URL.
In your example, it should probably be request()->segment(2) or request()->segment(3) based on the number of segments the URL has.
YourControllor:
use Illuminate\Support\Facades\URL;
file.blade.php:
echo basename(URL::current());
It was useful for me:
request()->path()
from www.test.site/news
get -> news
I just had the same question. In the meantime Laravel 8. I have summarised all the possibilities I know.
You can test it in your web route:
http(s)://127.0.0.1:8000/bar/foo || baz
http(s)://127.0.0.1:8000/bar/bar1/foo || baz
Route::get('/foo/{lastPart}', function(\Illuminate\Http\Request $request, $lastPart) {
dd(
[
'q' => request()->segment(count(request()->segments())),
'b' => collect(request()->segments())->last(),
'c' => basename(request()->path()),
'd' => substr( strrchr(request()->path(), '/'), 1),
'e' => $lastPart,
]
)->where('lastPart', 'foo,baz'); // the condition is only to limit
I prefer the variant e).
As #Qevo had already written in his answer. You simply make the last part part of the request. To narrow it down you can put the WHERE condition at the route.
Try with:
{{ array_pop(explode('/',$_SERVER['REQUEST_URI'])) }}
It should work well.

Laravel form open with multiple parameters

I am trying to pass variables with form open with following code:
{{ Form::open(['method' => 'PATCH','route' => ['note.update','project','1','1']]) }}
Here is my NoteController.php file
Class NoteController extends BaseController{
public function update($belongs_to,$unique_id=0,$note_id=0){
return $unique_id;
}
}
routes.php file is
Route::resource('note', 'NoteController');
Why I am only able to access $belongs_to variable and $unique_id and $note_Id are always 0 as given as default value??
That's because the routes registered with Route::resource only take one url parameter.
Take a look a this
So what you need to do is use this route:
Route::patch('note/{belongs_to}/{unique_id?}/{note_id?}', 'NoteController#update');
If you want to keep the other routes from Route::resource just add it before Route::resource
Route::patch('note/{belongs_to}/{unique_id?}/{note_id?}', 'NoteController#update');
Route::resource('note', 'NoteController');
If you don't want to add the route like this, you'll have to use query parameters to pass additional information

Is there a way to set a default url parameter for the Route class in Laravel 4?

I'm trying to set up sub-domain based routing in Laravel 4 and I've hit a bit of an annoyance...
My route group looks like this:
Route::group(array('domain' => '{company}.domain.com'), function() {
// ...
});
Which seems to work fine, however, I need to specify the company parameter for every route/url I generate. I.e:
{{ HTML::linkRoute('logout', 'Logout', ['company' => Input::get('company')]) }}
Is there any way to specify the company parameter as static/global, so it is automatically added to any links I specify, unless otherwise overwritten/removed?
Unfortunately, no (I haven't seen any evidence in the router or HTMLBuilder that you can). You could, however, make an HTML macro... Example:
HTML::macro('lr', function($link, $title) {
$company = !empty(Input::get('company')) ? Input::get('company') : "";
return HTML::linkRoute($link, $title, ['company' => $company]);
});
Then call it - instead of HTML::linkRoute, use HTML::lr('logout', 'Logout')
Just an idea.

Resources