Apply Middleware auth to all routes except `editPostJob/id` in Laravel - laravel

I am trying to apply auth middleware to all routes except "editPostJob" route but it didnt work as there is an id in url(http://127.0.0.1:8000/editPostJob/1).
Everytime i tried to go to that link it redirects me to login page.
in controller I tried:
public function __construct()
{
$this->middleware('auth')->except(['index', 'confirm','editPostJob']);
}
but it didnt work.
Any idea what should i do ?
thanks for any help.

I was able to solve it by doing:
public function __construct()
{
$this->middleware('auth')->except(['index', 'confirm', 'yourMethod']);
}
public function yourMethod(Request $request) //select statement
{
if (\Auth::check() == false) {
$is_read = "true";
} else {
$is_read = strip_tags($this->isLoggerOwnerOfPost($request->id));
}
$jobs = DB::table('jobs')->where('job_id', $request->id)->get();
return view('editPostJob', compact('jobs'))->with('is_read', $is_read);
}
Thanks Anurat !

Related

laravel 6 redirect back to page after login using socialite package [duplicate]

I have a page with a some content on it and a comments section. Comments can only be left by users who are signed in so I have added a login form to the page for users to sign in with (this only shows if they are not already logged in).
The problem I have is that when the user signs in they get redirected back to the home page and not the page they were previously on.
I have not changed the login method from the out of the box set-up.
Can anyone suggest a simple way to set the redirect url. My thoughts are that it would be good to be able to set it in the form.
Solution for laravel 5.3:
In loginController overwrite the showLoginForm() function as this one:
public function showLoginForm()
{
if(!session()->has('url.intended'))
{
session(['url.intended' => url()->previous()]);
}
return view('auth.login');
}
It will set the "url.intended" session variable, that is the one that laravel uses to look for the page which you want to be redirected after the login, with the previous url.
It also checks if the variable has been set, in order to avoid the variable to be set with the login url if the user submit the form with an error.
For Laravel 5.5, following code worked for me by just updating LoginController.php
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
Please use redirect()->intended() instead in Laravel 5.1
You can also see more about it here: http://laravel.com/docs/5.1/authentication
For Laravel 5.3
inside App/Http/Controllers/Auth/LoginController
add this line to the __construct() function
$this->redirectTo = url()->previous();
So the full code will be
public function __construct()
{
$this->redirectTo = url()->previous();
$this->middleware('guest', ['except' => 'logout']);
}
It works like a charm for me i'm using laravel 5.3.30
For Laravel 5.4, following code worked for me by just updating LoginController.php
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
Session::put('backUrl', URL::previous());
}
public function redirectTo()
{
return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
}
The Laravel 5.6, When user insert wrong credentials then login page will reload and session(['link' => url()->previous()]); will take login URL in link variable. So the user will redirect to a login page again or redirect to /home if login success. So to avoid these below code working for me! After that no matter how much time user insert wrong credentials he will redirect after login to exactly where he was before login page.
Update or overwrite public function showLoginForm() in LoginController.
public function showLoginForm()
{
if (session('link')) {
$myPath = session('link');
$loginPath = url('/login');
$previous = url()->previous();
if ($previous = $loginPath) {
session(['link' => $myPath]);
}
else{
session(['link' => $previous]);
}
}
else{
session(['link' => url()->previous()]);
}
return view('auth.login');
}
Also, Update or Overwrite protected function authenticated(Request $request, $user) in LoginController.
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}
If you want to redirect always to /home except for those pages with comments, then you should overwrite your redirectTo method in your LoginController:
public function redirectTo()
{
return session('url.intended') ?? $this->redirectTo;
}
On all pages where you want to remain on the site, you should store the url for one request in the session:
public function show(Category $category, Project $project){
// ...
session()->flash('url.intended' , '/' . request()->path());
}
Redirect to login with the current's page url as a query string:
login
In your LoginController check if exists and save the query string in session then redirect to the url after login
public function __construct() {
parent::__construct();
if ( \request()->get( 'redirect_to' ) ) {
session()->put( 'redirect.url', \request()->get( 'redirect_to' ) );
}
$this->middleware( 'guest' )->except( 'logout' );
}
protected function authenticated(Request $request, $user) {
if(session()->has('redirect.url') {
return redirect( session()->get( 'redirect.url' ) );
}
}
Look into laravel cheat sheet
and use:
URL::previous();
to go to the previous page.
Laravel 5
(maybe 6 also, not tested, if someone knows it please update the answer)
add this to LoginController:
protected function redirectTo(){
return url()->previous();
}
Note: if present the field $redirectTo , remove it
in your RedirectIfAuthenticated.php change this code
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/contactus');
}
return $next($request);
}
please notice to :
return redirect()->intended('/contactus');
Inside your template file you can just use:
{{ url()->previous() }}
To redirect from the controller you should use
return redirect()->back();
or Just
return back();
use Illuminate\Support\Facades\Redirect;
public function Show_Login_Form()
{
$back = Session::put('url_back',url()->previous());
$current = url()->current();
if(Session::get('user_id'))
{
if ($back == $current) { // don't back Login Form
return Redirect::to('home');
}
elseif (Session::has('url_back')) {
return Redirect::to('home');
}
else{
return redirect()->back();
}
}
else{
if ($back == $current) {
return Redirect::to('home');
}
else{
Session::put('url_back',url()->previous());
}
return view('account.customer-account.login');
}
}
public function signin_user(Request $request) // Login post
{
$username = $request->input_username_login;
$password = md5($request->input_password_login);
$result = DB::table('tbl_user')
->where([['user_email',$username],['user_password',$password]])
->orWhere([['user_phone',$username],['user_password',$password]])
->first();
if($result){
Session::put('user_id', $result->user_id );
Session::put('user_name', $result->user_name);
Session::put('user_username', $result->user_username);
Session::put('user_avatar', $result->user_avatar);
return Redirect::to(Session::get('url_back')); // Back page after login
} else {
Session::put('message_box', 'Error !!!');
return redirect()->back();
}
}
You can use redirect back with Laravel 5:
<?php namespace App\Http\Controllers;
use Redirect;
class SomeController extends Controller {
public function some_method() {
return Redirect::back()
}
}
Use Thss
return Redirect::back('back-url')

if esle condition not working inside constructor for middleware in laravel 5.4

I can use only one middleware at a time..inside a constructor..I want to use if else condition inside constructor or two middleware.
I can use only only middleware inside constructor & if else condition also not working
Example are follows
If else
class HRJob extends Controller
{
public function __construct()
{
if(Auth::guard('admin'))
{
$this->middleware('auth:admin');
}
else
{
$this->middleware('auth');
}
}
public function userdetails()
{
dd(Auth::user());
}
}
Two middleware
class HRJob extends Controller
{
public function __construct()
$this->middleware('auth:admin');
$this->middleware('auth');
}
public function userdetails()
{
dd(Auth::user());
}
}
in your case, there is no need for two middleware.
public function __construct()
{
$this->middleware('auth');
}
is equivalent to whatever you are trying to do since 'auth' is still valid for 'auth:admin'.
but you can still put your middleware in the Routes files (web.php/api.php) like this
Route::group(['middleware'=>'auth:admin'],function (){
Route::get('/', 'HRJob#userdetailsAdmin');
});
Route::group(['middleware'=>'auth'],function (){
Route::get('/', 'HRJob#userdetails');
});
hope this helps.
---edit---
in your case, with two different table for auth and without creating a custom middleware for a "any auth", you are just missing the check() method:
if (Auth::guard('admin')->check()) {
$this->middleware('auth:admin');
} else {
$this->middleware('auth');
}
wich is equivalent to
if (!Auth::guard('admin')->check()) {
$this->middleware('auth');
}

Passing shared variable after login with Laravel 5.5

i created a method in order to share datas with all views of my application.
For this i created a class EntityRepository where i store the datas I want to share with all views.
Those data are displayed in the layout NOT the view.
class EntityRepository
{
use App\Valuechain;
public function getEntities()
{
$vcs = Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->get();
return $vcs;
}
}
When I want to send datas to the methods I simply call the getEntities() method... For example :
public function index(EntityRepository $vcs)
{
$entitiesLists = $vcs->getEntities();
// My code here ...
return view('admin.pages.maps.sectors.index', compact('entitiesLists', 'myVars'));
}
In this specific case it works fine and i don't have issue. My issue concerns the landing page after login.
In the loginController :
I defined the redirectTo variable this way :
public $redirectTo = '/admin/home';
For specific reasons I had to override the authentificated() method in the LoginController in order to check if my app is configured or need to be setup ...
protected function authenticated(Request $request, $user)
{
$langCount = Lang::count();
if ($langCount == 0) {
return redirect()->to('admin/setup/lang');
}
else {
//return redirect()->to('admin/home');
return redirect()->action('BackOffice\StatsController#index');
}
}
The concerned index() method is sending the variable onto the view :
public function index(EntityRepository $vcs)
{
$entitiesLists = $vcs->getEntities();
return view('admin.home', compact('entitiesLists'));
}
Whatever the return i make i have error message...
Undefined variable: entitiesLists (View: C:\wamp64\www\network-dev\resources\views\admin\partials\header-hor-menu.blade.php)
I finally solved this issue by changing my routes :
Route::group(['prefix' => 'admin'], function () {
Route::get('/', function (){
$checkAuth = Auth::guard('admin')->user();
if ($checkAuth) {
return redirect('/admin/main');
}
else {
return redirect('admin/login');
}
});
});
In my loginController i changed :
public $redirectTo = '/admin/home';
to :
public $redirectTo = '/admin/main';
Finally :
protected function authenticated(Request $request, $user)
{
$langCount = Lang::count();
if ($langCount == 0) {
return redirect()->to('admin/setup/lang');
}
else {
return redirect()->to('admin/main');
}
}

Laravel domain group without having to pass domain parameter to controllers

I have all my routes in a domain group but I would like to avoid having the domain as a parameter in each controller method.
So I would like to avoid having this everywhere:
public function show($domain, $id) {}
and would like to just keep it as
public function show($id) {}
I was able to partially make it work with $request->route()->forgetParameter('subdomain') placed in a middleware but it doesn't work in the case of calling redirect()->action('SomeController#show') from a controller method.
Here are some more details:
First, all routes are in a domain group.
Route::middleware(['some_middleware'])->domain('{subdomain}' .website.com)->group(function () {
// .. All routes
} );
Then, in some_middleware I have
public function handle($request, Closure $next) {
// ..
$request->route()->forgetParameter('subdomain');
return $next($request);
}
Then where it doesn't work:
class SomeController {
public function process()
{
// ...
redirect()->action('SimpleController#show', ['simple' => $id]);
}
}
The error I'm getting is:
Missing required parameters for [Route: ] [URI: simples/{simple}].
This only works if I explicitly pass in the subdomain variable.
class SomeController {
public function process()
{
// ...
redirect()->action('SimpleController#show', ['subdomain'=>'some_subdomain', 'simple' => $id]);
}
}
Can anyone suggest a "fix" for this? Thanks in advance :)
With Laravel 5.5+, you can use URL::defaults to set request-wide values for things like the route helper.
https://laravel.com/docs/5.6/urls#default-values
public function handle($request, Closure $next) {
// ..
$subdomain = $request->route('subdomain');
URL::defaults(['subdomain' => $subdomain]);
$request->route()->forgetParameter('subdomain');
return $next($request);
}
You could create a wrapper helper for the action() helper:
if (! function_exists('actionSub')) {
function actionSub($name, $parameters)
{
return action($name, $parameters + ['subdomain' => request()->route('subdomain')]);
}
}
Then use it:
redirect(actionSub('SimpleController#show', ['simple' => $id]));
If someone has a more elegant solution for this, it will be great to see it.

CodeIgniter routing issue, advice how to do it

I'm not CI programmer, just trying to learn it. Maybe this is wrong approach, please advice.
my controller(not in sub directory) :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index($msg = NULL) {
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function process_logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}
And a route for login :
$route['user/login'] = 'users/index';
Problem is when I wanna logout, it shows me 404 because I do not have it in my route :
$route['user/process_logout'] = 'users/process_logout';
and in my view I put logout
When I add that, it works, and that is stuppid to add a route for everything. What I'm I doing wrong, please advice.
Thank you
Don't know why you are trying to implement login feature in index() function. However since you said you are learning CI I'm telling something about _remap() function.
Before that. You can try the following routing:
$route['user/:any'] = 'users/$1';
$route['user/login'] = 'users/index';
If you want to take value immediately after controller segment you need to use _remap() function and this function may be solve your routing problem, i mean you don't need to set routing. Lets implement your code controller 'users' using _remap() function.
class Users extends CI_Controller {
private $sections = array('login', 'logout');
function __construct() {
parent::__construct();
}
public function _remap($method)
{
$section = $this->uri->segment(2);
if(in_array($section, $this->sections))
call_user_func_array(array($this, '_'.$section), array());
else show_404(); // Showing 404 error
}
private function _login()
{
$msg = $this->uri->segment(3);
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function _logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}

Resources