I have created a route to pass dynamic parameters to controller but when i serve url it shows me for not found here is my route and controller I create
Routes
Route::get('/admin/managers/{method}/{id}',
[
SetupController::class, 'managers'
]
);
Controller
public function managers($method, $id) {
if($method == 'create') {
return view('admin.pages.create-manager');
} elseif($method == 'create') {
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
When i serve url localhost/public/managers it shows me 404 not found but when i serve localhost/public/managers/create/1 the page is loading then can anyone hep me out why exactly is it happening
as we discussed in the comments what you need is to make your parameters optional like below
change your route like this
Route::get('/admin/managers/{method?}/{id?}', [SetupController::class, 'managers']);
and your controller like this
public function managers($method=null, $id=null) {
if ($method == 'create') {
return view('admin.pages.create-manager');
} elseif ($method == 'edit') { // change here
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
and also don't forget to run at the end
php artisan optimize
The issue is that in your code, the second if condition is checking for the same value 'create', this resulting in a 404 error for the URL "localhost/public/managers".
To resolve this issue, change the second if condition to check for another value. For example, if you want to show the page with the id, use the following code:
public function managers($method, $id) {
if ($method == 'create') {
return view('admin.pages.create-manager');
} elseif ($method == 'show') {//or anything else
echo $id;
return view('admin.pages.create-manager');
} else {
return view('admin.pages.managers');
}
}
Related
only fist two line execute in this code last two role not check how can solve this problem
$input = $request->all();
$this->validate($request,[
'email'=>'required|email',
'password'=>'required'
]);
if(auth()->attempt(['email'=>$input["email"], 'password'=>$input['password']]))
{
if(auth()->user()->role == 'accountadmin')
{
return redirect()->route('accountadmins');
}
else if(auth()->user()->role == 'maintainadmin')
{
return redirect()->route('maintainadmins');
}
if(auth()->user()->role == 'superadmin')
{
return redirect()->route('superadmins');
}
if(auth()->user()->role == 'subscriber')
{
return redirect()->route('subscriberss');
}
else
{
return redirect()->route('home');
}
}
else
{
return redirect()
->route("login")
->with("error",'Incorrect email or password');
}
if(auth()->user()->role == 'superadmin')
{
return redirect()->route('superadmins');
}
if(auth()->user()->role == 'subscriber')
{
return redirect()->route('subscriberss');
}
without checking this role go next step. i have four login role using auth . but when i execute the only first two role check after that go next step . i try to else if else if but same problem
You could use a switch control structure here. Like this:
switch (auth()->user()->role) {
case 'accountadmin' : return redirect()->route('accountadmins');
case 'maintainadmin' : return redirect()->route('maintainadmins');
case 'superadmin' : return redirect()->route('superadmins');
case 'subscriber' : return redirect()->route('subscribers');
default : return redirect()->route('home');
}
Although its much better to use middlewares or route -> permission binding, but to simply answer your question you can do the following:
$routes = [
'accountadmins' => 'accountadmin',
'maintainadmins' => 'maintainadmin',
'superadmins' => 'superadmin',
'subscribers' => 'subscriber'
];
Using array_search:
if (false !== $route = array_search(auth()->user()->role, $routes)) {
return redirect()->route($route);
} else {
return redirect()->route('home');
}
Personally I recommend to use a permission package such as spatie/laravel-permission it is very well maintained and documented:
https://spatie.be/docs/laravel-permission/v5/basic-usage/middleware#package-middleware
https://github.com/spatie/laravel-permission
How to print out data within function beforeAction? I want to make some verification before each action in a controller, therefore if some condition occurs in beforeAction I should print out data and prevent further execution, for example, JSON:
[
status: "error",
msg: "access denied"
]
I try to even inner redirect to another controller, but it doesn't work.
public function beforeAction($action)
{
$request = Yii::$app->request;
if ( ! checkByToken($request->get('token')) && $this->getRoute() != 'web/abonent/token_error') {
\Yii::$app->runAction('web/abonent/token_error');
return true;
}
return parent::beforeAction($action); // TODO: Change the autogenerated stub
}
But maybe there an another concept of doing so. I just need to check the condition before any actions and print our result or let the action execute.
To prevent further execution:
public function beforeAction($action) {
return false; // key point
}
To print out data within beforeAction:
public function beforeAction($action) {
// set response format = json:
Yii::$app->response->format = Response::FORMAT_JSON;
// then, set the response data:
Yii::$app->response->data = [
'status' => 'error',
'msg' => 'access denied'
];
return false;
}
I think will be better
public function beforeAction($action)
{
$request = Yii::$app->request;
if ( ! checkByToken($request->get('token')) && $this->getRoute() != 'web/abonent/token_error') {
$action = 'error';
}
return parent::beforeAction($action); // TODO: Change the autogenerated stub
}
Action name must be 'actionError'
I am trying to create a filter in Laravel so that only admins are allowed to access some URLs.
What I have done is,
Route::filter('admin', function()
{
if (Auth::user()->permission != -1)
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('/');
}
}
});
in the app/filters.php file.
But I am getting an eror like this if I try yo access admin's url-
Users table is like this-
Can anyone help please?
This is because Auth::user() is null. Auth::user() is only available when the user is logged in. You will need to do Auth::check() first before calling anything on the intended user model
Route::filter('admin', function()
{
if (!Auth::check() || Auth::user()->permission != -1)
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('/');
}
}
});
How to send the url's parameter to filter.php and retrieve it there?
Route
Route::get('/users/{id}/edit', 'UsersController#edit');
I want to send the {id} from the above URL to the filter.php and retrieve it's value there
something like this
Route::filter('access', function($id)
{
if (Auth::check())
{
if (Auth::user()->is_admin != 1 && Auth::user()->id = $id) {
return View::make('users.noaccess');
}
}
else
{
return Redirect::guest('/')->with('error', 'Please login to access this page');
}
});
and then used beforeFilter to bind the filter to the method
$this->beforeFilter('access', array('only' => 'edit'));
The filter closure function accepts a number of parameters (http://laravel.com/docs/4.2/routing#route-filters). You can rewrite your filter like this:
Route::filter('access', function($route) {
$id = $route->parameter('id');
if (Auth::check()) {
if (Auth::user()->is_admin != 1 && Auth::user()->id = $id) {
return View::make('users.noaccess');
}
} else {
return Redirect::guest('/')->with('error', 'Please login to access this page');
}
});
I'm new to Yii. I have an issue with authenticating for different locations. I have an app that needs admin and user authentication. While admin uses google auth, users use the de facto username/password combo.
Below is my code. What am I missing. Basically, I want when a user types /admin her/she should get the admin login - which I have sorted and when he/she types /account/login the user should get the regular username/password login.
public function beforeAction($action)
{
$host = $_SERVER ['REQUEST_URI'];
if (!isset(Yii::app()->session['user_type']))
{
if ($host != '/account/login' && $host != '/admin')
{
//header('Location: /access');
header('Location: /account/login');
}
/*else if ($host != '/admin')
{
header('Location: /admin');
}*/
}
else
{
$access = $this->access();
$currentCont = ucfirst($this->getUniqueId());
if (!empty($access))
{
if (!in_array($currentCont, $access))
{
Yii::app()->session->clear();
Yii::app()->session->destroy();
header('Location: /account/login');
}
}
return parent::beforeAction($action);
}
return parent::beforeAction($action);
}
I believe that .htaccess might be translating your requests from 1 to another.
Even if your url might be /admin it might be translating to something else with .htaccess and that is actually your URI.
Either that or I am very tired now :(.
I found a not so elegant solution for this issue:
if ($currentCont != 'admin' && $host != 'login')
{
echo '<meta http-equiv="refresh" content="0; url='.Yii::app()->createUrl('/account/login').'">';
}
else
{
echo '<meta http-equiv="refresh" content="0;url='.Yii::app()->createUrl('/admin').'">';
}
It strikes me as strange you would be doing this with a beforeAction. If I understand your need, I would write two actions. One would be site/login and would handle the regular users and one would be site/admin and would handle your admin users.
I'd have the regular login for your normal users:
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
and then I'd have a second action for the admin case.
public function actionAdmin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
<do google auth stuff>
if (<authenticated by google>) {
return $this->goBack();
} else {
<deal with authentication failure>
}
}