Laravel 5.6 - Get Route By Name In Controller - laravel

Within my login controller there is a hardcoded URL string which sets where to redirect to once the user has logged in. I am trying to make this dynamic by getting the route by name:
protected $redirectTo = '/home';
Updated To:
protected $redirectTo = route('home');
However the above give the following error:
FatalErrorException (E_UNKNOWN)
Constant expression contains invalid operations
Is it possible to get the URL to the route by its name?

You can use
request()->route()->getName()
To get the url you would use
request()->url()
And the path
request()->path()
Current route method
request->route()->getActionMethod()
In the case of redirectTo you can override the function:
protected function redirectTo() {
return route('foo.bar');
}

Your problem is that you're not allowed to use a function call when declaring a property in your class. You should use your controller's constructor to set it:
class LoginController extends Controller
{
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->redirectTo = route('home');
}
}
Alternatively, you can define a redirectTo method which returns the location that you want the user to be redirected to after a successful login. You can then remove the $redirectTo property altogether:
class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function redirectTo()
{
return route('home');
}
}

You have to define a route named home
like this:
Route::get('/home', 'HomeController#index')->name('home');
or Route::get('/home', ['as' => 'home', 'uses' => 'HomeController#index']);

Another way to get route url
$route_url = \Request::route()->getURLByName("name of the route");

protected $redirectTo = route('home');
You cannot assign a function to property. That's why you are getting this error.
you can do this in your constructor like
public function __construct(){
$this->redirectTo = route('home')
}

This is the way which i use and it will work with you.just put this function in your LoginController to override authenticated function.
protected function authenticated(Request $request, $user)
{
return redirect()->route('your_route_name');
}

Related

Laravel Resource Routing not showing anything when directly call method

I am stuck in resource routing
when I enter url netbilling.test/customer it goes to customer index file but when I enter url netbilling.test/customer/index nothing is returned. Also guide me if I have to route different method than in resource what is the method for that.
here is my web.php,
Route::get('/dashboard', function () {
return view('dashboard/index');
});
Route::resource('/customer','CustomerController');
here is my customer controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Customer;
use App\Package;
use Redirect,Response;
class CustomerController extends Controller
{
public function index()
{
$packages = Package::get();
$customers = Customer::orderBy('id', 'DESC')->get();
return view('customer/index', compact('customers','packages'));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
}
}
Without custom route specification, this is how the index route maps to a Resource Controller, taken from Actions Handled By Resource Controller:
Verb
URI
Action
Route Name
GET
/photos
index
photos.index
So if you want URI /customer/index to work, then you need to specify this explicitly in your Controller:
use App\Http\Controllers\CustomerController;
Route::resource('customer', CustomerController::class);
Route::get('customer/index', [CustomerController::class, 'index'])->name(customer.index);

Passing Data in Login and Register Page Laravel 6

I create login and register function in Laravel 6 with scaffold function, and i got this LoginController:
<?php
...
...
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
I want to pass a data DB::table('terms_condition')->get() to login view, how should i do?
Put this method in LoginController
public function showLoginForm()
{
$terms_condition = DB::table('terms_condition')->get();
return view('auth.login',compact('terms_condition'));
}
showLoginForm() is from AuthenticatesUsers trait which is used by your LoginController. You have to put this method in LoginController.
Inside your login controller rewrite the function showLoginform
public function showLoginForm()
{
` $data = DB::table('terms_condition')->get();
return view('frontend.auth.login',compact('data'));
}
Or From your LoginController you can see that AuthenticateUsers
go to the Authenticate Users file and edit the showLoginForm as like this
public function showLoginForm()
{
` $data = DB::table('terms_condition')->get();
return view('frontend.auth.login',compact('data'));
}
And dont forget to use DB in the top
You can override the built-in showLoginForm() method in the LoginController
LoginController.php
use Illuminate\Support\Facades\DB;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.login',['terms'=>DB::table('terms_condition')->get()]); //pass your data here as a second argument
}
}
You can then access this in your blade view as $terms
A different way to go about it: use a View Composer. This will run when the view is rendered so you can pass data to it this way:
view()->composer('auth.login', function ($view) {
$view->with('something', DB::table(...)->get());
});
// or View::composer(...) if you prefer
You can add that at a Service Provider's boot method. No overriding anything.
Laravel 6.x Docs - Views - View Composers View::composer()

How to get current user id in constructor in laravel?

I am using laravel 5.7, but i can't get current user id in __construct().
I also tried Auth:id(), but it also not working.
How to get current user id in constructor?
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
return $next($request);
});
dd($this->id);
}
}
Current output is null.
You can only access the session in the closure. Just refactor your code to this:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
You can now use the value $this->id in your controller methods.
In the example in your question, after you've set the value $this->id, you continue with the request. Since you try to access $this->id outside of the scope of the closure, it still is null in the datadump.
After return you will not go to next statement that's why it is not print.
If you want to use this in view then no need to pass in view you can simply access logged user id like this
{{Auth->user->id}}
if you wan to use this in controller make sure you are logged in.
Sometime session expired then you will not get user id
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public $id;
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->id = Auth::user()->id;
dd($this->id);
return $next($request);
});
}
}
The easiest solution is to create a middleware and call it later in the constructor.
php artisan make:middleware FoobarMiddleware
I recommend putting an alias in Kernel.php
protected $routeMiddleware = [
...
'foobar' => \App\Http\Middleware\FoobarMiddleware::class,
]
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware('foobar');
}
I recommend changing the focus of how you are creating everything

Declare a variable to be used in all methods Laravel

What is the best way to declare a variable to be used in all the methods within my controllers and my models:
example .. I want to replace:
Auth::user()
by:
$this->user
What would be the best way to do it?
For Laravel 5.3.4+
Declare the property in your controller and then you can do it like this in its __construct method:
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
For versions below, you can just $this->user = Auth::user(); inside __construct.
Reference: https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors
If you attempt to set a user in your Controller.php's __construct method you will find it won't work.
This won't work:
public function __construct()
{
$this->user = auth()->check() ? auth()->user() : null;
}
This is by design, according Taylor, the framework's creator. He discourages setting your user in the base controller - but, it's up to you how you want to do things. There is a way around this. If you wanted $this->user to be accessible in every controller, you would add this to your Controller.php file:
protected function setUser()
{
$this->user = auth()->check() ? auth()->user() : null;
}
Then in your __construct method call it:
public function __construct()
{
$this->setUser();
}
Now, you can access this->user from any controller method. It will be null if not set, but if you are using Laravel's standard auth guard you shouldn't have much of a problem with unauthenticated users getting through.

Laravel 5.3: How to use Auth in Service Provider?

I am passing a value in shared view by taking value from table. I need to know user ID for the purpose but Auth::check() returns false. How do I do it? Below is code:
public function boot()
{
$basket_count = 0;
if (Auth::check()) { //always false
$loggedin_user_id = Auth::user()->id;
$basket_count = Cart::getBasketCount();
}
view()->share('basket_count', $basket_count);
}
OK turns out that ServiceProviders are not place for such things. The best thing is a Middleware. So if you want to call Auth, create middleware and pass value to views.
public function handle($request, Closure $next)
{
$basket_count = 0;
if ($this->auth) { //always false
$loggedin_user_id = $this->auth->user()->id;
$basket_count = Cart::getBasketCount($loggedin_user_id);
}
view()->share('basket_count', $basket_count);
return $next($request);
}
You can use authentication directly in the controller file. Adding it in the middleware is a cleaner way of doing the authentication.
For eg. In CategoriesController.php
...
class CategoryController extends Controller {
/**
* CategoryController constructor.
*/
public function __construct()
{
$this->middleware('auth');
}
...
If you want to have a look at a complete example
http://deepdivetuts.com/basic-create-edit-update-delete-functionality-laravel-5-3

Resources