LARAVEL $router->bind for only backend(admin) - php

In RouteServiceProvider I have:
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
and url for admin is "/admin/user/1".
but for frontend url is "/user/username"
So I want to check if this is "admin" or "frontend" url and for admin bind user but for frontend don't bind user:
$adminRoute = //check if this is admin or frontend url ("/admin/user/1" or "/user/username")
if($adminRoute){
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
}else{
//nothing
}
PS. I don't want change findOrFail() function to find user by username I want disable binding for non admin urls.

Try this:
Route::group(array('prefix' => 'admin'), function() {
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
});

Related

how to customize Auth::routes in laravel

I hope you are the best.
I'm trying to create a multi-language feature in my Laravel app.
but I don't know how to insert Auth::routes in my web routes file to support my multi-language.
this code works for me but Auth::routes links don't set correctly.
the app can identify target language but in Auth::routes() links arent' correctly.
for example, all the page is based on target language but links in the local language. (target is en_us but links in fa_IR)
Route::get('/', function ()
{
// echo "befpreRpikte".$request->cookie('language').'<br/>';
// return ('CookieInRoute\'/\''.request()->cookie('language'));
return redirect(App::getLocale().'/welcome');
})->middleware(CheckLanguage::class);
Route::get('/{locale}',function($locale)
{
return redirect($locale.'/welcome');
});
Route::get('{locale}/welcome',function($locale)
{
//echo('CookieInRoute\'/\''.request()->cookie('language'));
//die(App::getLocale());
return view('welcome');
})->middleware(CheckLanguage::class);
Route::group(['prefix' =>App::getLocale()], function () {
Auth::routes();
// Route::get(App::getLocale().'/login','HomeController#login');
//Route::get('{locale}/home','HomeController#index');
});
and my middle ware is:
public function handle($request, Closure $next)
{
//echo(var_dump(request()->cookie('language')));
//if(empty(request()->cookie('language')))
cookie()->queue('language',$this->checkUserIsoCode($request->path()),60);
App::setLocale($this->checkUserIsoCode($request->path()));
// dd(request()->cookie('language'));
return $next($request);
}
private function checkUserIsoCode($path)
{
// echo '<br/> <c> c</c></br>';
$available_locales=config('app.all_locales');
if($path==null || $path=="/")// => "/" in addressbar
{
try
{
$userLocale=\Location::get(request()->ip())->countryCode;
}
catch(Exception $e)
{
$userLocale="fa_IR";
}
}
else
$userLocale=$path[0];//locale =>/locale/address
foreach($available_locales as $locale)
{
if(strpos($locale,$userLocale)!==false)//if $locale contain userlocale
{
$userLocale=$locale;
break;
}
}
if(!in_array($userLocale,$available_locales,TRUE))
$userLocale=config('app.fallback_locale');
return $userLocale;
}
You could group all your routes so all of them get locale as prefix:
Route::group(['prefix' => '{locale}'], function() {
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
})->middleware(CheckLanguage::class);
This blog post seems to solve what you are trying to do:
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

How to restrict authenticated users to only access their on profile

I am stuck with users profile feature, I want only authenticated users to access their own profile only.
User with id: 1 can only access route /applicants/profile/1, otherwise return 404 Not found?
class ApplicantProfileController extends Controller
{
public function show(Applicant $applicant)
{
return view('applicant.show', compact('applicant'));
}
}
route::group(['prefix' => 'applicants', 'middleware' => 'auth:applicant'], function() {
Route::get('/profile/{applicant}', 'Profiles\ApplicantProfileController#show');
});
You can chech whether the logged user and the parameter user are the same by using the Illuminate/Support/Facades/Auth facade like this:
public function show(Applicant $applicant)
{
if (Auth::id() == $applicant->id) {
return view('applicant.show', compact('applicant'));
}
return abort(404);
}

Custom Filter for Laravel Route

I'm trying to make some custom filters for my Laravel application.
In filter.php I have
Route::filter('admin', function()
{
if (Auth::guest() AND ! Auth::user()->isAdmin()) {
return 'Not Authorized';
}
});
User.php model
public function isAdmin()
{
if($this->role==1) return true;
else return false;
}
And finally in the Route:
//SECTIONS ONLY FOR ADMIN
Route::group(array('prefix' => 'admins', 'before' => array('admin')), function(){
Route::get('/frontoffice', 'FrontofficeController#index');
Route::get('/frontoffice/about', 'FrontofficeController#about');
Route::get('/frontoffice/research', 'FrontofficeController#research');
});
I'm logged in as an Admin in my application, but still I'm getting NotFoundHttpException when I try to access the above URLs in the route.
Any idea why?

Laravel 4 redirect issue with login page

I am using laravel 4 and here is my AdminController file :
class AdminController extends BaseController {
protected $layout = "admin.layout";
public function __construct() {
// security for the forms and access
$this->beforeFilter('csrf', array('on'=>'post'));
$this->beforeFilter('auth.admin' , array('except' =>array('getIndex','postSignin')));
// using this one to display user value if login and is admin
if (Auth::check() && Auth::user()->isAdmin()){
$this->user = Auth::getUser();
View::share('user', $this->user);
}
}
// main admin page
public function getIndex(){
$this->layout->content = View::make('admin.login');
}
// get the dashboard page
public function getDashboard() {
$this->layout->content = View::make('admin.dashboard');
}
// missing pages all redirect to dashboard if user is logged in.
public function missingMethod($parameters = array()){
if (Auth::check() && Auth::user()->isAdmin())
$this->getDashboard();
else
$this->getIndex();
}
Here is my filters.php file :
Route::filter('auth.admin', function()
{
if(!Auth::check() && !(Auth::user()->isAdmin())){
return Redirect::guest('admin');
}
});
in my routes.php file I am doing this:
Route::controller('admin', 'AdminController');
here is what I want if you could help me :_
1) . I want to clean up my code where there is not that much checking for if user is logged and isAdmin.
2). right now if you are logged in and you go to "admin/" , it will show you the login page ? how could I fix it in an effective way.
3). also if you are not logged in and you go to "admin/dashboard" it will show you dashboard content ? how to fix
Thank you in advance for all your help :)
You can use route groups and use a single filter to validate them
Check the docs
http://laravel.com/docs/routing#route-groups
Add this in your routes.php file:
Route::group(array('before' => 'auth.admin'), function() {
Route::controller('admin', 'AdminController');
})
Declare filter in filters.php file:
Route::filter('auth.admin', function(){
// Assumed you have a '/login' url
if (Auth::guest() || (Auth::check() && !Auth::user()->isAdmin())) {
return Redirect::guest('login');
}
});
Also make sure you have the user()->isAdmin() method in your User model that you are using and it checks whether the user is an admin or not and returns a Boolean value, TRUE if the user is an admin otherwise FALSE.

Redirecting to the same route /user/{{username}} Laravel 4+

I am newbie who wants to make before filter which will check what I want and return redirect with error or success to the same /user/{{username}} profile.
So here is my filter before function
Route::filter('test', function()
{
$param = Request::segment(2);
if($para = 'username')
{
Session::flash('error', 'blabla!');
return Redirect::route('profile-public');
}
else
{
Session::flash('secces', 'xxx!');
return Redirect::route('profile-public');
}
});
here is my route
Route::group(array('before' => 'test'), function()
{
Route::get('/user/{username}', array('as' => 'profile-public','uses' => 'ProfileController#user'));
});
and my ProfileController public function
public function user($username)
{
$user = User::where('username', '=', $username);
if($user->count()){
$user = $user->first();
return View::make('profile.user')
->with('user', $user);
}
return App::abort(404);
}
So my problem is how to get those redirection work, I tried to search google etc and I could not find any answers. Sorry for the mess in the post it's my first post here and sorry for my english.
Example go to public profile of /user/admin --> filter check --> redirect to /user/admin with error or success.
You don't need a redirect here, just use this filter :
Route::filter('test', function()
{
$param = Request::segment(2);
if ($para = 'username')
{
Session::flash('error', 'blabla!');
}
else
{
Session::flash('secces', 'xxx!');
}
});

Categories