How is Localization in Laravel implemented? - php

I want to implement localization on my website using Laravel 5.5.
However, I am not sure what the standard practice when using localization should be. I have used the LocalizationController module from the Laravel documentation. My goal is to have the localization option selected via a dropdown. Then the user's selection should be remember.
Do I store their selection in a database for future use?
Or, is this something to keep in a cookie?
Side note:
(I want to avoid having their selection in the url. I'll either pass the data in a request or get method.)

For registered and logged-in users i recommend to store the users language in the database. Everytime a user logs in the application should set the language for the current user. Maybe you take a closer look on middleware. Build a language middleware, register it as new middlewaregroup and assign it to every route (-group) you need. A middleware could look like this:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class LanguageMiddleware
{
public function handle($request, Closure $next)
{
if(Auth::check()){
// user is logged in
App::setLocale(Auth::user()->language);
return $next($request);
}
App::setLocale(config('app.locale'));
return $next($request);
}
}
Now register the new middleware in app/Http/Kernel.php as new middleware-group under protected $middlwareGroups:
// other middleware-groups
'language' => [
\App\Http\Middleware\LanguageMiddleware::class
]
Finally assign middelware-group to route (-group):
Route::group(['middleware' => ['language']], function(){
// Routes...
});
Unfortunately there is no build-in function to show a dropdown-language-select. But you can simply build a blade-partial which you can integrate in your navbar or where-ever you want to show/use it. You could ask new users during registration for their preferred language.
Guests/unregistered users could use the dropdown. By default they should see the default language.
Hopefully this helps you.

Related

How to Restrict controllers or routes for different type of users in API

I'm working on a project with laravel. in my project there's two type of users one of them are admins and other one is normal users.
btw project is only provides API and there's no blade views.
I give a token to any user or admin logins with the api. and application will identify user or admin by sending that token with an authorization header and I check if token is validate and the user type is admin then give access to the admin features for that client.
here's my code for this part:
$admin = Auth::guard('admin-api')->user();
if ($admin) {
// allow to use admin features
}
else {
return response()->json(['error' => 'token is invalid'], 401);
}
I read something about applying Restrictions on a controller class in laravel and it was written there to add a constructor like this into controller class:
public function __construct() {
$this->middleware('admin-api');
}
and also there's something like that just for Restricting routes. like this
but I just want to know is it necessary to add same constructor to my controller class while the project just provides API? or the way that I'm doing is correct?
You are doing it right.
I would prefer restricting the request via routes, so there is no need to add constructor on each new Controllers.
Route::middleware(['admin-api'])
->group(function () {
Route::get('cart', 'Carts\CartController#retreive');
Route::post('cart/coupon', 'Carts\CartCouponController#addCoupon');
Route::delete('cart/coupon', 'Carts\CartCouponController#deleteCoupon');
Route::delete('cart/flyer', 'Carts\CartController#deleteFlyer');
});
This will apply the admin-api middleware on all the routes in the group and there is no need to add a constructor on Carts\CartController and Carts\CartCouponController, just to have middleware restriction.

Showing subpages based on a session in Laravel 5.8

I am begginer in Laravel. I am use Laravel 5.8 in my project.
I need to do something so that a specific route can be viewed by a user with a php adult = 1 session.
I have route:
Route::get('/', 'FrontendController#index')->name('index');
Route::get('/sample1', 'FrontendController#sample1')->name('sample1');
The SAMPLE1 view is for users with php adult = 1 session.
If the user does not have such a session - it must be automatically redirected to # index
How can you do this?
You can achieve this by creating a custom middleware, take a look at the documentation here:
https://laravel.com/docs/5.8/middleware
Instead of using session, you can maintain a user is adult or not on the users table, which means you can access this info via authenticated user (which is available throughout the whole app).
For e.g. in your app, use php artisan make:auth and this will scaffold out everything you need to for a register/login system. Before you run the migration, add a new field to the create_users_table migration, e.g. $table->boolean('adult')->default(false);
Then once the migration is ran, you can create a new middleware using: php artisan make:middleware CheckAdult with something like this:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckAdult
{
public function handle($request, Closure $next)
{
if (!auth()->check() || !auth()->user()->adult) {
return redirect('/');
}
return $next($request);
}
}
The above middleware will redirect anyone who is not logged in or have adult = 0 back to index page, otherwise continue with their request.
Then register the middleware and use it in the routes; as per the documentation.
you can use auth and middleware to achieve this. the simple logic would be something like this: $id = Auth::user()->adult; in your controller to check for users. ofcorse adult is a field in your table.
//on top of your controller place this
public function __construct()
{
$this->middleware('auth');
}
//control logic to check user
if($adult==1){
//perform unique task
}else{
return redirect('/')->with('message','You are not permitted')
}

modify Laravel Auth registration page

I am trying to modify the Laravel Auth registration system in that I'd like to require that a token parameter be provided in order for the user to be able to access the registration page (ie http://website.dev/register/{tokenhere}). Below is the pertinent code:
From my routes\web.php file:
Route::get('/register/{token}', function() {
//
})->middleware('token');
From my \App\Http\Middleware\CheckToken.php file:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckToken
{
public function handle($request, Closure $next)
{
if($request->token != 'test') { #just hard coding something here for testing purposes
return redirect('home');
}
return $next($request);
}
}
I also added 'token' => \App\Http\Middleware\CheckToken::class to the $routeMiddleware array in \App\Http\Kernel.php
However, I go to http://website.dev/register and I'm able to access the page, despite not providing a token parameter. I can also see that if I provide the 'test' parameter that the middleware is looking for (http://website.dev/register/test), I get a blank page.
Hoping someone can point me in the right direction. I'm quite new to MVC and Laravel. Thanks for your time!
You can just create custom route, like /register/{token} and handle this token in the controller. Maybe even set in middleware group if you want.

Protect routes in Laravel 5.1

I am using Laravel 5.1 for my project. I am trying to secure Routes and make sure only logged in user can access certain routes. I am aware about middlewares but I am wondering if anyone post an example or a link explaining about middleware and how to protect a page using middleware.
Thanks
To build on the answer given by Joe Rose, you can also specify the middleware in your controller rather than in your routes.php file.
E.g you could have your routes set out like
Route::get('/example', 'ExampleController#index');
Route::post('/example/post', 'ExampleController#post');
Route::resource('blog', 'BlogController');
And then inside your controller reference it like so:
class ExampleController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
//....
If you're looking for more info, check out the link to the docs Joe gave, and also this blog post which explains what middleware is really well and how to create your own if you need to.
You are correct about using middleware. The included Auth middleware is what you should use, as long as you are also using the included Auth controller to authenticate users. You would write your route like this:
Route::get('/page', array(
'uses' => 'Controller#method',
'middleware'=>'auth'
));
(The above example is using a GET request, but it could other request types, like POST for example).
This will use the default behavior of the middleware which checks to see if the user is logged in (authenticated). You can also extend or overwrite the built-in functions to allow you to direct the application on where to send the user if they are or are not logged in, etc. Laravel's official documentation is a good starting point: link

Laravel 5 new auth: Get current user and how to implement roles?

I am currently experimenting with the new Laravel 5 and got the authentication to work (register/login).
To get the authenticated user in my controller I currently inject Guard into the controller action:
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
class ClientController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Guard $auth)
{
return view('client.index', ['user' => $auth->user()]);
}
...
First Question: Is this the recommended way?
Second Question: How would I go about implementing some kind of roles/permissions? Something like client.edit, client.add, ... Does Larval 5 offer some kind of convenience here?
How would I set the necessary role/permission for a route/controller action?
I am thinking that I might need to write my own middleware for that. Any suggestions on how to approach the problem?
After spending some more time on Laravel 5 I can an answer my own question:
Is injecting Guard the recommended way? No: If you need to access Auth in your view, you can do so already like this:
#if( Auth::check() )
Current user: {{ Auth::user()->name }}
#endif
This uses the Auth facade. A list of all available facades is in config/app.php under aliases:
What if I need Auth in my controller? Injecting an instance of Guard like shown in the question works, but you don't need to. You can use the Auth facade like we did in the template:
public function index()
{
if(\Auth::check() && \Auth::user()->name === 'Don') {
// Do something
}
return view('client.index');
}
Be aware that the \ is needed before the facade name since L5 is using namespaces.
I want to have permissions/roles using the new auth mechanism in L5: I implemented a lightweight permission module using the new middleware, it is called Laraguard. Check it out on Github and let me know what you think: https://github.com/cgrossde/Laraguard
UPDATE: For the sake of completeness I want to mention two more projects. They provide everything you need to save roles and permissions in the DB and work perfectly together with Laraguard or on their own:
https://github.com/caffeinated/shinobi
https://github.com/romanbican/roles
If you want make your own custom authentification, you need to keep the User model from Laravel 5 with all the dependency. After you will be able to login your user in your controller. Dont forget to put (use Auth;) after the namespace of your controller.

Categories