i just installed laravel 5.2, and i created auth register, login, and reset password, but now i want create a index of my project where all user (also not logged) can access. i tryed to create
Route::get('/',HomeController#home');
But this view is enable only for users logged.
MY ROUTES
Route::auth();
Route::get('/home', 'HomeController#index');
// POST - FORM CREA
Route::get('/crea-regalo', 'PostController#form');
Route::post('/crea-regalo', 'PostController#creaPost');
// LISTA ANNUNCI PRINCIPALE
Route::get('/', 'HomeController#home');
MY HOME CONTROLLER
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('id','DESC');
return view('home', compact('posts'));
}
public function home()
{
$posts = Post::all();
return view('index', compact('posts'));
}
}
How can i create routes of view where ALL users can access?
Thank you for your help!
Hi write separate controller to access page to all because you have written auth middleware in contructor
public function __construct()
{
$this->middleware('auth');
}
Similar like
class GuestController extends Controller
{
public function __construct()
{
}
public function home()
{
$posts = Post::all();
return view('index', compact('posts'));
}
}
In route
Route::get('/home', 'GuestController#home');
or else you can do like this
$this->middleware('auth', ['except' => ['home']]);
this will able to access home page for all .In your constructor add this
public function __construct()
{
$this->middleware('auth', ['except' => ['home']]);
}
Put those route which you want to allow only authenticated user in middleware auth as follows:
Route::group(['middleware' => ['auth']], function () {
//your routes
})
And for those routes which all user can access put that out side the above group.
Related
I have an ongoing Laravel project and I'm currently learning. So there will be multiple users that can register for the system. For example, user1 created an account and made transactions and changes on his account. When user2 register and login, user2 sees everything in user1's account instead of a fresh blank dashboard to get started with. I tried adding middleware->('auth'); in my routes but it didn't change anything.
HomeController
<?php
namespace App\Http\Controllers;
use App\MoneyTrade;
use App\MoneyTradeDeposit;
use App\Withdrawal;
use Illuminate\Http\Request;
use Laravel\Ui\Presets\Vue;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$balance = Withdrawal::sum('amount');
return view('dashboard', compact('moneytrades', 'moneytradeDeposits', 'amountSum', 'balance'));
}
public function dashboard()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$withdrawal = Withdrawal::all();
$balance = Withdrawal::sum('amount');
return view('dashboard', compact('moneytrades', 'moneytradeDeposits', 'amountSum',
'withdrawal', 'balance'));
}
public function stocks()
{
$amountSum = MoneyTradeDeposit::sum('amount');
return view('home.stocks', compact('amountSum'));
}
public function support()
{
return view('home.support');
}
public function withdrawal()
{
$moneytrades = MoneyTrade::all();
$moneytradeDeposits = MoneyTradeDeposit::all();
$amountSum = MoneyTradeDeposit::sum('amount');
$withdrawal = Withdrawal::all();
$balance = Withdrawal::sum('amount');
return view('home.withdrawal', compact('moneytrades', 'moneytradeDeposits', 'amountSum',
'withdrawal', 'balance'));
}
}
web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/send-mail', 'SendMailController#send')->middleware('auth');
Auth::routes();
Route::get('register/agreement', 'Auth\RegisterController#show')->name('register.agreement');
Route::get('/home', 'HomeController#index')->name('home')->middleware('auth');;
Route::get('/dashboard', 'HomeController#dashboard')->name('home.dashboard')->middleware('auth');
Route::get('/my-account', 'MyAccountController#index')->name('myaccount.index')->middleware('auth');
Route::patch('/my-account/update', 'MyAccountController#update')->name('myaccount.update')->middleware('auth');
Route::get('/stocks', 'HomeController#stocks')->name('home.stocks')->middleware('auth');
Route::get('/support', 'HomeController#support')->name('home.support')->middleware('auth');
Route::get('/withdrawal-information', 'HomeController#withdrawal')->name('home.withdrawal')->middleware('auth');
Route::resource('withdrawal', 'WithdrawalController')->middleware('auth');
Route::resource('moneytrade', 'MoneyTradeController')->middleware('auth');
Route::resource('moneytrade-deposit', 'MoneyTradeDepositController');
Route::get('/account-removed', 'MoneyTradeController#destroy')->name('mt.delete')->middleware('auth');
Route::get('/trading-account', 'MoneyTradeController#view')->name('mt.view')->middleware('auth');
Route::get('/trading-account/deposits', 'MoneyTradeController#deposit')->name('mt.deposit')->middleware('auth');
How can I achieve this and prevent other users to access other dashboards that's not their own? I don't have roles and just normal users. I just want to prevent one user from accessing other user's dashboard. Thank you!
I am currently trying to build a user registration system with edit fields. At the edit portion, I had to create separate views for editing/updating personal details, email, and passwords.
I started with an empty resource controller. it had only one edit method. Hence I added additional edit methods. Each method can have a separate route. However, I have a hard time having a separate route for each update method in each section as the resource has only one route like this in docs:
PUT/PATCH /photos/{photo} update photos.update
Is there any workaround for this?
Controller
class UserController extends Controller
{
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
public function index()
{
return view('users.index');
}
public function edit_personal(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.personal', ['users' => $user_profile]);
}
public function update_personal(Request $request, User $user)
{
// How to write route for this method.
}
public function edit_email(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.email', ['users' => $user_profile]);
}
public function update_email(Request $request, User $user)
{
// How to write route for this method.
}
public function edit_password(User $user)
{
$user_profile = User::find($user->id);
return view('users.edit.password', ['users' => $user_profile]);
}
}
Routes
Auth::routes(['verify' => true]);
Route::get('/', function () {
return view('welcome');
});
Route::get('/users/{user}/personal', 'UserController#edit_personal')->name('users.personal');
Route::get('/users/{user}/email', 'UserController#edit_email')->name('users.email');
Route::get('/users/{user}/password', 'UserController#edit_password')->name('users.password');
Route::resource('users', 'UserController');
Basically I have separated edit portion of user controller into personal, email and password sections and they have separate forms. I want to write update functions for each section in UserController.
don't know why are you using separate forms for updating each fields while you can do it in a single form. however you can use either put/patch or post method for updates. here's i am using post for example.
routes:
Route::get('users/{user}/personal', 'UserController#edit_personal')->name('users.personal');
Route::post('users/{user}/personal', 'UserController#update_personal')->name('users.update-personal');
Route::get('users/{user}/email', 'UserController#edit_email')->name('users.email');
Route::post('users/{user}/email', 'UserController#update_email')->name('users.update-email');
Route::get('users/{user}/password', 'UserController#edit_password')->name('users.password');
Route::post('users/{user}/password', 'UserController#update_password')->name('users.update-password');
as you are using route model binding you can directly get the object.
public function edit_personal(User $user)
{
return view('users.edit.personal', ['users' => $user]);
}
public function update_personal(Request $request, User $user)
{
//validation goes here
$user->update([
'value' => $request->value,
...........
]);
}
I've a User Role column on my User's table.
stands for Super Admin,
stands for other users
I've checked a lot of Laravel Tutorials and none of them has helped me about solving this issue.
I've found ways like replacing the whole Laravel's Login Controller and replacing Authenticate Users trait with ours own. I want to solve my problem with minimal code change. Is it possible?
How do I implement it with minimal code changes in this Trait method?
public function login(Request $request)
{
$this->validateLogin($request);
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
You could do something as supersimple as adding a isSuperAdmin function to the User model. After logging in you just call this function on the user whenever you need to check.
In model User.php
public function isSuperAdmin()
{
return $this->user_role == 1;
}
Then you could also make a middleware that's using this function.
php artisan make:middleware SuperAdmin
In the handle function of this middleware (app/http/middleware/SuperAdmin.php):
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->isSuperAdmin()) {
return $next($request);
}
return redirect('some-route-for-unauthorized-users');
}
Then in your routes (probably web.php), you can use this middleware to protect routes:
Route::group(['middleware' => ['auth', 'superadmin']], function () {
... put protected routes here ...
});
Solution
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest')->except('logout');
}
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['role'] = '1';
return $credentials;
}
I want to redirect user, if not authenticated, to my index page (which is the login page)
Can't seem to make it work and i really got confused with the routing.
HomeController
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return redirect()->guest('/');
}
}
Routing
// Index
Route::get('/', [
'as' => 'index',
'uses' => 'UserController#index'
]);
UserController
The routing as you see redirects to a User Controller at index function, which is the below :
*has __construct() so it uses the middleware 'auth'.
public function __construct()
{
$this->middleware('auth');
}
public function index(){
// If user is logged
if(Auth::check()) {
// If user has NOT submitted information form redirect there, otherwise to categories
if(!Auth::user()->submitted_information)
return redirect()->route('information');
else
return redirect()->route('categories');
}
else
return view('index', ['body_class' => 'template-home']);
}
Handler.php
And the unauthenticated function inside middleware of auth (Exceptions/Handler.php)
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('index');
}
The error i get right now is the below :
InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.
This error happens because of the line of
return redirect()->route('index'); in the above unauthenticated function.
What am i missing here? If you need any more information please feel free to ask.
EDIT : Until now, if i remove from UserController the __construct() method, and insert in web.php to all the routes what middleware to use, it works.
For example
Route::get('/categories', [
'as' => 'categories',
'uses' => 'UserController#showCategories'
])->middleware('auth');
But i am trying to find, without specifying there what middleware to use, to use it automatically.
Build your route like below code:
Route::group(['middleware' => ['auth']], function() {
// uses 'auth' middleware
Route::resource('blog','BlogController');
});
Route::get('/mypage', 'HomeController#mypage');
Open your middleware class named RedirectIfAuthenticated and then in handle fucntion
you write below code:
if (!Auth::check()) {
return redirect('/mypage'); // redirect to your specific page which is public for all
}
Hope it will work for you.
Your route should be like
// Index
Route::get('/','UserController#index')->name('index);
see here for more about routing.
Try
Route::get('/','UserController#index',['middleware'=>'auth'])->name('index);
i have just make a sub authentication Middleware in my Laravel 5.2 application which use Laravel session to store data.
I can put my data to Laravel session
But when i want to delete that variable form session it working for only that request when page redirect or someone reload the page that variable still exists.
In My controller File
class SubmissionController extends Controller
{
public function login(Request $request){
if($request->session()->has('submission')) return redirect('/submission-directory');
return view('submission.login');
}
public function dologin(Request $request){
if(!$request->get('password') == "reader") return redirect('/submission-directory/login')->withErrors('errors.wrong-password');
Session::put('submission','yes');
$redirect = $request->session()->pull('submission_redirect','/submission-directory');
return redirect($redirect);
}
public function index(Request $request){
dump($request->session()->all());
$request->session()->forget('submission');
dump($request->session()->all());
die('coming here');
}
}
but when I reload the page You can session is still exists..
Notice :: I have put all the routs in web Middleware group
Route.php
Route::group(['middleware' => 'web'], function () {
Route::group(['prefix'=>'/submission-directory'],function(){
Route::get('/login','submissionController#login');
Route::post('/login',['as'=>'submission.login','uses'=>'SubmissionController#doLogin']);
Route::group(['middleware'=>'submission'],function(){
Route::get('/','SubmissionController#index');
});
});
Try this
IN Controller :
use Session;
public function index(Request $request)
{
dump(Session::all());
Session::forget('submission');
print_r((Session::all());
die;
}