So I'm trying Laravel 9 localization with parameters in a controller response basicly like this:
return redirect()->route('index')->with('success', __('messages_success', ['name' => 'Fleet']));
On my resources/lang/en.json:
{
"message_success_create":":Name created successfully.",
"message_success_update":":Name updated successfully.",
"message_success_delete":":Name deleted successfully.",
}
It works like a charm.
Suddenly I got a devil whisper like "I'm 100% sure that I can make it simpler & shorter!" then I changed those line in my controller to be:
return redirect()->route('index')->with('success', __('messages_success', ['name' => 'Fleet', 'action' => __('created')]));
In resources/lang/en.json:
{
"message_success":":Name :action successfully.",
}
It got shorter and simpler right?
But it doesn't work! While it always successfully return text in default English but no other else.
Is this only on my machine or Laravel localization does not support __() in __() ?
I tried with trans() but no different.
Related
I created an API (store) that saves the data on the database and returns 201 if successful or 404 if not.
if ($visit->save()){
$visit->view_visit = [
'href' => 'api/v1/visit/' . $visit->id,
'method' => 'GET'
];
$response = [
'msg' => 'Visit created.',
'visit' => $visit
];
return response()->json($response, 201);
}
$response = [
'msg' => 'Error during creation.'
];
return response()->json($response, 404);
It works perfectly. Using postman you can see that the status will be <<201 Created>>.
This API should be used in two ways: called by another application or called by a Laravel form. This is the question:
How do I call it in a way if it successful, it will load a given view on the browsers?
In other words, is there a way to make the form call a route (the api itself, something like ../api/visit/) and in case of success loads the other view? Also, I would like to pass the content of response['msg'] to this new view.
I know I could do it inside the store method by filtering the HTTP referrer, but I would like to keep the controller code strictly to manage the record creation. Besides that, I have to send the 201/404 codes along with the returned data.
I also considered creating another controller to handle the API response and then call the form, but it still sounds too much -- it's supposed to be easy, I guess.
In laravel you can use a helpful method which determines if the request that has been sent is an AJAX request or just a normal request, which is:
$request->wantsJson()
So, Inside your controller in the return function, you will make an if statement:
if ($request->wantsJson()) {
return response()->json();
}else{
return view(...);
}
I use this package for localization https://github.com/mcamara/laravel-localization and it works fine in most cases except with one POST request.
When I try to access:
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'auth'],
],
function () {
Route::post('bsSearch', 'BrandSpendingsController#search')->middleware('premium');
}
I get an MethodNotAllowedHttpException ... When I switch it to GET it works fine... However it works for english language. If I switch the url to http://localhost/de/bsSearch, it throws an error.
Route::get('bsSearch', 'BrandSpendingsController#search')->middleware('premium');
I am really not sure why because this one works fine and it is a POST method as well:
Route::post('editUserProfile/{id}', 'UserController#edit');
I use Laravel 5.3.
EDIT
The english url works because I've set 'hideDefaultLocaleInURL' => true, in laravellocalization.php and when it hides the "en" prefix in URL. If i set it to false, it throws an error for English as well.
Here is an answer
it is better to localize only GET routes by puting them to localized group and don't put there another routes
if you need to localize another methods like POST, PUT, PATCH, DELETE, you should localize your url as described here
I did move from Lumen to Laravel and now converting my project over. Everything is working except the validation. For some reason, if I try to validate, it just redirects to the welcome.blade.php view. What could cause this?
I am using only the API part of routes, not the view. I am not dealing with views. I am using the stateless part of Laravel.
According to documentation, I can validate like this:
$this->validate($request, [
'title' => 'required|unique|max:255',
'body' => 'required',
]);
If validation passes, your code will keep executing normally. However,
if validation fails, an
Illuminate\Contracts\Validation\ValidationException will be thrown.
I also tried to force it to return JSON response without success:
$validator = $this->validate($request, ['email' => 'required']);
if ($validator->fails()) {
$messages = $validator->errors();
return new JsonResponse(['status' => 'error', 'messages' => $messages]);
}
However, mine doesn't fail but just returns the welcome view with response code of 200. I have tried pretty much all the possible validation methods from the documentation and from google. Non of them are working.
I even tried with clean laravel install, declared one test route and test controller which had the validation and the result is the exact same.
Is the validation even meant to be compatible with the restful/stateless part of Laravel?
Any suggestion is much appreciated.
1- first the unique key needs a table, per example if you want the email to be unique in the users table you do as follows:
'email' => 'required|unique:users',
I think may be you have placed your route in route/web.php file. Replace that code from web.php to api.php
Try to place your API endpoints in route/api.php file.
And remember you need to add prefix /api in your route.
Ex : test.com/api/users.
In a controller, I need to return translated message in an Ajax json response as:
$body['message'] = __("Duplicated");
$this->response->body(json_encode($body));
$this->response->statusCode(202);
$this->response->type('json');
return $this->response;
But the translation is not looked up. However, in a template, I am able to get this working:
<?= __("Duplicated");?>
I know I can use the Ajax layout and write a template, but in this case the message body is very short, I need to return a Status Code other than 200. How can I do this in a controller in CakePHP 3?
It seems to be a CakePHP bug (Not a bug, see comments below). I have in app.php
'App' => [
...
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
...
]
and in AppController::beforeRender(), According to http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html#changing-the-locale-at-runtime I could override with this (but in fact that does not work):
I18n::locale('zh');
When I change config/app.php to
'App' => [
...
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'zh'),
...
]
It works.
I've been stuck with a problem in Laravel 5.
Question: Is is possible to have a default function in a Laravel controller if no other functions are activated?
Explanation:
In routes I have this:
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
'/projects' => 'ProjectController'
]);
By doing this I can call functions in my ProjectController like getIndex or postCreate. I'd like to have the following
/projects/create, /projects/edit/{id} etc. AND /projects/{slug} <- name of project. Before, when I set all my routes individually I could just place the /projects/{slug} at the bottom and it would check for that at last.
I thought of a solution: go trough all the functions, if none of them are executed do the default function (for /projects/{slug})
How would I do this? If more code is needed, please ask! :)
I think you might be looking for missingMethod:
public function missingMethod($parameters = array())
{
// code goes here
}
Read more in the Laravel Documentation.