how can i get language value randomly in laravel controller? - laravel

class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$value = "home";
$value2 = Lang::get('home.'.$value.'');
}
}
output :'home.home'.
But i need value from language file.
please guide me to get this.

It seems like you are trying to get a translation. For that you can use the trans helper method like this:
//In your resources/lang/{some_lang_code}/home.php
return [
'home' => 'My translation',
];
//In your controller
$value = "home";
$value2 = trans('home.'.$value); //My translation

Related

Laravel How to get Route Profile based on Route Name

I have this route:
Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController#index'])
I've been tried to use $routeProfile=route('test');
But the result is returned url string http://domain.app/test
I need ['as'=>'test','custom_key'=>'custom_value'] so that I can get the $routeProfile['custom_key']
How can I get 'custom_value' based on route name ?
For fastest way, now I use this for my question:
function routeProfile($routeName)
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
$action = $route->getAction();
if (!empty($action['as']) && $routeName == $action['as']) {
$action['methods'] = $route->methods();
$action['parameters'] = $route->parameters();
$action['parametersNames'] = $route->parametersNames();
return $action;
}
}
}
If there's any better answer, I will be appreciate it.
Thanks...
Try this:
use Illuminate\Support\Facades\Route;
$customKey = Route::current()->getAction()['custom_key'];
I believe you are looking for a way to pass variable to your route
Route::get('/test/{custom_key}',[
'uses'=>'TestController#index',
'as'=>'test'
]);
You could generate a valid URL like so using
route('test',['custom_key'=>'custom_key_vale'])
In your view:
<a href="{route('test',['custom_key'=>'custom_key_vale'])}"
In your controller method:
....
public function test(Request $request)
{
$custom_key = $request->custom_key;
}
....
You can try one of the below code:
1. Add use Illuminate\Http\Request; after namespace line code
public function welcome(Request $request)
{
$request->route()->getAction()['custom_key'];
}
2. OR with a facade
Add use Route; after namespace line code
and use below into your method
public function welcome()
{
Route::getCurrentRoute()->getAction()['custom_key'];
}
Both are tested and working fine!

Cakephp 3 does not work for the default language

Sorry for my english, but I hope you will understand me.
Simplified code looks like this:
//in bootstrap.php
ini_set('intl.default_locale', 'deu');
// MainMenusTable.php
public function initialize(array $config)
{
parent::initialize($config);
...
$this->addBehavior('Translate', ['fields' => ['title']]);
...
}
//in controller - THIS WORKS!
public function add()
{
I18n::locale('eng');
$mainMenu = $this->MainMenus->newEntity();
if ($this->request->is('post')) {
$mainMenu = $this->MainMenus->patchEntity($mainMenu, $this->request->data);
$this->MainMenus->save($mainMenu)
}
$this->set(compact('mainMenu'));
}
// in controller BUT THIS DOES'T WORK:
public function add()
{
I18n::locale('deu');
$mainMenu = $this->MainMenus->newEntity();
if ($this->request->is('post')) {
$mainMenu = $this->MainMenus->patchEntity($mainMenu, $this->request->data);
$this->MainMenus->save($mainMenu)
}
$this->set(compact('mainMenu'));
}
I have the same problem when I read the record
//in controller - THIS WORKS!
I18n::locale('eng');
$query = $this->MainMenus->find('all')->order(['MainMenus.id' => 'ASC'])->all();
// in controller BUT THIS DOES'T WORK:
I18n::locale('deu');
$query = $this->MainMenus->find('all')->order(['MainMenus.id' => 'ASC'])->all();
For 'deu' I manually entered records.
Do you know what the problem is?
Thanks!
This is a solution to the problem from https://github.com/cakephp/cakephp/issues/8416:
The behavior assumes that you store the records in the default language. If the current locale is the same as the default language, then it will just return the records in the database instead of fetching from the translations table.
The title will not be saved in the i18n table for the default language, that is only done for other languages.

Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path#index'
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path#index' with $id, $start, and $end?
});
There is no way to call a controller from a Route:::get closure.
Use:
Route::get('/path/{id}/{start?}/{end?}', 'Controller#index');
and handle the parameters in the controller function:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
This helped me simplify the optional routes parameters (From Laravel Docs):
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Or if you have a controller call action in your routes then you could do this:
web.php
Route::get('user/{name?}', 'UsersController#index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
I hope this helps someone simplify the optional parameters as it did me!
Laravel 5.6 Routing Parameters - Optional parameters
I would handle it with three paths:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Note the order - you want the full path checked first.
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Find more details here (Laravel 7) : https://laravel.com/docs/7.x/routing#parameters-optional-parameters
You can call a controller action from a route closure like this:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
What I did was set the optional parameters as query parameters like so:
Example URL:
/getStuff/2019-08-27?type=0&color=red
Route:
Route::get('/getStuff/{date}','Stuff\StuffController#getStuff');
Controller:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
Solution to your problem without much changes
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
return App\Http\Controllers\HomeController::Path($id,$start,$end);
});
and then
class HomeController extends Controller
{
public static function Path($id, $start, $end)
{
return view('view');
}
}
now the optimal approach is
use App\Http\Controllers\HomeController;
Route::get('/path/{id}/{start?}/{end?}', [HomeController::class, 'Path']);
then
class HomeController extends Controller
{
public function Path(Request $request)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
//your code
return view('view');
}
}

declaring class level variables in codeigniter

I am new to CI and what I want to do is to have a class level variable (which e.g is an array). But it seems like CI, despite all high bragging, doesn't support this feature. Nothing has been mentioned in the user guide about it. There is a heading called private functions and variables but the text has been seemingly kept silent regarding variables.
I want to have something like :
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->model('orders', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
$data['result'] = $this->Testmodel->get_reports();
$this->load->view('test', $data);
}
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($arr_CoreCountry as $key => $value)
{
$data['result'] = $this->Orderstatsmodel->get_orderStats($key);
}
// $data['result'] = $this->Orderstatsmodel->get_orderStats(0);
$this->load->view('orderstats', $data);
}
Remember, when I declare $arr_CoreCountry variable at the place as it is in this post, I constantly see a syntax error message.
When I place it some where inside any function then of course, it gets out of scope and I keep getting an error messag that $arr_CoreCountry is an undefined variable.
So the question is where do I define it?
Expect a quick response as half of my day has been wasted just because of this s*** from codeigniter.
This should work:
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($this->arr_CoreCountry as $key => $value)
// etc
}
you are omitting the $this-> in your original code.
Edit
Here was my test code ~
class Testing extends CI_Controller {
protected $foo = array('test'=>'foo', 'bar'=>'baz');
function index() {
foreach($this->foo as $k => $v) {
echo $k . ' = ' . $v . '<br />';
}
}
}
// outputs:
test = foo
bar = baz
perhaps you can post your syntax errors as they appear to be missing from your original post.
You have a syntax array declaration error. Please try to declare array like this:
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
Please check out this site for array manual: http://php.net/manual/en/language.types.array.php
I solved the problem myself.
There are two things which I changed
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
was changed to
var $arr_CoreCountry = array(0=>'se', 1=>'fi',2=>'de');
and
foreach ($arr_CoreCountry as $key => $value)
was changed to
foreach ($this->arr_CoreCountry as $key => $value)
I was missing $this but when I put it there, it was still not working. When I changed protected to var, it worked.
Thanks everyone for your input...

How to change the value of a variable inside a controller from a view file (html)?

I followed this tutorial: http://codeigniter.com/wiki/Internationalization_and_the_Template_Parser_Class/
The controller that loads the language is this one:
<?php
class Example extends Controller {
function Example() {
parent::Controller();
# Load libraries
$this->load->library('parser');
# Load language
$this->lang->load('example', 'english');
}
function index() {
# Load variables into the template parser
$data = $this->lang->language;
# Display view
$this->parser->parse('example', $data);
}
}
?>
In order to change the language I have to manually change english to say spanish in the controller.
What's the best way the user can do this from the index.php file (view)?
The best thing to do is have the user select a supported language on some page, set it as a session variable and call it when ever you need to load a language
$language = $this->session->userdata("language");
$this->lang->load("example", $language);
$data = $this->lang->language;
$this->parser->parse("example", $data);
EDITED BELOW
If you're using CodeIgniter and you're new to this, I wouldn't suggest messing with the index.php file.
You want to do it inside your controller by loading a form where they can pick their language and storing it in the session. I'd also suggest autoloading your session library.
The controller:
<?php
class Home extends Controller {
function Home()
{
parent::Controller();
$this->load->library("session");
}
function index()
{
$language = $this->session->userdata("language");
$this->lang->load("example", $language);
$data = $this->lang->language;
$this->parser->parse("example", $data);
}
function set_lang()
{
if( ! $this->form_validation->run())
{
$this->load->view("select_language_form");
}
else
{
$language = $this->input->post('language', TRUE);
$this->session->set_userdata('language', $language);
redirect('home' 'location');
}
}
}

Resources