How to access my lang files from controller in laravel 5
Asked Answered
N

2

11

Converting from Laravel 4 to Laravel 5. Trying to access Lang file in controller like so:

$var = Lang::get('directory/index.str1');

That gives me: Class 'App\Http\Controllers\Lang' not found. However

{{Lang::get('directory/index.str1');}}

Works fine in a view

Nattie answered 30/7, 2015 at 16:15 Comment(0)
S
12

You are missing a use statement for the Lang class and PHP is looking for it in the current namespace, that's why you see App\Http\Controllers\Lang in the error message.

It works in the view, as view files are executed in global namespace, where the Lang facade exists.

In order for your code to work do one of the following:

  1. Use fully qualified class name for Lang

    $var = \Lang::get('directory/index.str1');
    
  2. Add use statement at the top of your controller

    <?php namespace App\Http\Controllers;
    use Lang;
    
Swop answered 30/7, 2015 at 16:28 Comment(0)
Z
14

You can as well use the __ helper (Works for Laravel 5.5, 5.6 and 5.7 ... not sure about the other versions). e. g if your array of strings are stored in a file called messages.php inside lang directory, to get a string with the key myString, use the following in the controller:

__('messages.myString');

In blade template you would use:

@lang('messages.myString')
Zaidazailer answered 9/2, 2019 at 16:14 Comment(2)
in blade can i use this {{__('messages.myString')}}Ozonide
When using __('file.key') on function that we define in app\Http\Controllers and share it to all view, the text still on default lang (which is english). Idk why it's like that. But if it just using it on function on custom controller that return view the page, it's working (translate the text)Westbrooks
S
12

You are missing a use statement for the Lang class and PHP is looking for it in the current namespace, that's why you see App\Http\Controllers\Lang in the error message.

It works in the view, as view files are executed in global namespace, where the Lang facade exists.

In order for your code to work do one of the following:

  1. Use fully qualified class name for Lang

    $var = \Lang::get('directory/index.str1');
    
  2. Add use statement at the top of your controller

    <?php namespace App\Http\Controllers;
    use Lang;
    
Swop answered 30/7, 2015 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.