How to get translate message in controller Laravel? - laravel

I have file excel.php by the path /resources/lang/en/excel.php
Then in controller I tried to fetch word by key:
use Lang;
echo Lang::get('excel.idEvent');
Also I tried:
dd(echo __('excel.idEvent'));
Whats is right way to do that?

First, your excel.php file must be in the right format:
<?php
return [
'welcome' => 'Welcome to our application'
];
The right way to get it on your blade template in fact it is:
echo __('excel.welcome');
or
echo __('Welcome to our application');
The way to do it on your controller is:
use Lang;
Lang::get('excel.welcome');
If you are not using Facades: use \Illuminate\Support\Facades\Lang;
You can also use the trans() function, ex:
Route::get('/', function () {
echo trans('messages.welcome');
});

If you use JSON translation files, you might have to use __().
Here are all the ways to use:
#lang('...') // only in blade files
__('...')
Lang::get('...')
trans('...')
app('translator')->get('...')
Lang::trans('...')
They all defer to \Illuminate\Translation\Translator::get() eventually.

Related

laravel blade include files with relative path

In laravel blade system when we want to include a partial blade file we have to write the full path every time for each file. and when we rename a folder then we will have to check every #include of files inside it. sometimes it would be really easy to include with relative paths. is there any way to do that?
for example we have a blade file in this path :
resources/views/desktop/modules/home/home.blade.php
and I need to include a blade file that is near that file :
#include('desktop.modules.home.slide')
with relative path it would be something like this :
#include('.slide')
is there any way to do this?
if someone still interest with relative path to current view file, put this code in the boot method of AppServiceProvider.php or any provider you wish
Blade::directive('relativeInclude', function ($args) {
$args = Blade::stripParentheses($args);
$viewBasePath = Blade::getPath();
foreach ($this->app['config']['view.paths'] as $path) {
if (substr($viewBasePath,0,strlen($path)) === $path) {
$viewBasePath = substr($viewBasePath,strlen($path));
break;
}
}
$viewBasePath = dirname(trim($viewBasePath,'\/'));
$args = substr_replace($args, $viewBasePath.'.', 1, 0);
return "<?php echo \$__env->make({$args}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>";
});
and then use
#relativeInclude('partials.content', $data)
to include the content.blade.php from the sibling directory called partials
good luck for everyone
you need to create custom blade directive for that, the native include directive doesn't work like that.
read this page to learn how to create custom blade directive :
https://scotch.io/tutorials/all-about-writing-custom-blade-directives
\Blade::directive('include2', function ($path_relative) {
$view_file_root = ''; // you need to find this path with help of php functions, try some of them.
$full_path = $view_file_root . path_relative;
return view::make($full_path)->render();
});
then in blade file you can use relative path to include view files :
#include2('.slide')
I tried to tell you the idea. try and test yourself.
There’s now a package doing both relative and absolute includes (lfukumori/laravel-blade-include-relative) working with #include, #includeIf, #includeWhen, #each and #includeFirst directives. I just pulled it in a project, it works well.
A sleek option, in case you want to organise view files in sub-folders:
public function ...(Request $request) {
$blade_path = "folder.subfolder.subsubfolder.";
$data = (object)array(
".." => "..",
".." => $..,
"blade_path" => $blade_path,
);
return view($data->blade_path . 'view_file_name', compact('data'));
}
Then in the view blade (or wherever else you want to include):
#include($blade_path . 'another_view_file_name')

How to call helper function in laravel 5.5

I am using laravel 5.5. I have created a helper.php in app\Http. I am calling this helper in my blade file by using
{!! Helper::functionName() !!}
this is working fine. but i want to hold this helper result in a variable like
{!! $Result=Helper::functionName() !!}
But currently this is printing this result. How to solve this. please help.
So that i can make any if condition on this $Result.
In my helpers.php
namespace App\Http\Helpers;
class Helper
{
public static function functionName()
{
return "mydata";
}
}
There is no point to use helper like this. You should run the helper in controller and pass calculated data into view. In most cases you shouldn't set any variables in views or make any calculations - those should be passed from controller to view and view should only use them.
In this case, you can use "<?php ?>".
So result:
<?php $Result=Helper::functionName(); ?>
may be this is not possible because in laravel "{{}}" this means echo "" so by default it will print the value. return the value from helper function and use in your blade

Using Blade directives outside of templates

Laravel 5.1: I defined a few custom directives inside a BladeServiceProvider (example below). Now I would like to use them outside of a view template to format strings (I am writing an EXCEL file with PHPExcel in a custom ExportService class). Is it possible to reuse my directives?
Blade::directive('appFormatDate', function($expression) {
return "<?php
if (!is_null($expression)) {
echo date(\Config::get('custom.dateformat'), strtotime($expression));
}
else {
echo '-';
}
?>";
});
The BladeCompiler has a compileString method, which allows you to use the Blade directives outside the views. :)
So, you can do things like this:
$timestamp = '2015-11-10 17:41:53';
$result = Blade::compileString('#appFormatDate($timestamp)');
You can use this:
use Illuminate\Support\Facades\Blade;
$timestamp = '2023-01-28 12:41:53';
Blade::render("#appFormatDate({$timestamp})");

Add parameter to Codeigniter URL

I have a problem when i try to add other parameter to URL.
before i use Codeigniter i add those parameters using JavaScript like this
test
but when i tried to do it with Codeigniter i don't know how.
<?php echo anchor("home/index/param1","test"); ?>
as i said i want to add this parameter for example my URL looks like this
home/index/param2
so when i click on test i want the URL to be like this
home/index/param2/param1
Take a look at CodeIgniter's URL Helper Documentation
The first parameter can contain any segments you wish appended to the URL. As with the site_url() function above, segments can be a string or an array.
For your example, you could try:
<?php
$base_url = 'home/index/';
$param1 = 'param1';
$param2 = 'param2';
$segments = array($base_url, $param1, $param2);
echo anchor($segments,"test");
?>
You can't do that with the form helper, you have to use your js function again :
echo anchor("home/index/param2", "test", array("onClick" => "javascript:addParam(window.location.href, 'display', 'param1');"));
It will produce :
test
But I don't see the point of dynamically change the href on the click event. Why don't you set it directly at the beginning ?
echo anchor("home/index/param2/param1", "test");

Laravel 4: include template with parameters in single line

I'm trying to save a blade template into a javascript variable but I can't figure out how to remove the line breaks from the template.
I looked at extending blade and created the following code based on BladeCompiler:compileInclude() which removes all line breaks, but only for templates without parameters.
Blade::extend(function($view, $compiler)
{
$pattern = $compiler->createMatcher('include_string');
return preg_replace($pattern, '$1<?php echo str_replace(array("\r","\n"), "", $__env->make($2, array_except(get_defined_vars(), array(\'__data\', \'__path\')))->render()); ?>', $view);
});
I know I could simply remove all line breaks from the template manually but I'm hoping there's a better way.
Has anyone done this before? Any help is appreciated.
I haven't found a way to create your own blade functions that can receive multiple values (or an array) and I don't think it is even possible by using "only" Blade::extend. Of course you could extend Laravel's BladeCompiler class and write much more powerful macros.
But instead I suggest you create a macro for removing the line breaks only.
Blade::extend(function($view, $compiler)
{
$pattern = $compiler->createMatcher('singleline');
return preg_replace($pattern, '$1<?php echo str_replace(array("\r","\n"), "", $2); ?>', $view);
});
And the use it either like this:
#singleline(View::make('view-name', array('foo' => 'bar')))
Or if you prefer the $__env syntax:
#singleline($__env->make('view-name', array('foo' => 'bar')))

Resources