How to properly define my authenticate routes in Laravel 7? - laravel

I am new to laravel and i am trying to define my routes.And the logic is "/" routing to "/login" if the user is not authenticated and "/login" routing to login view blade.Down below are the routes.
Auth::routes();
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
});
Route::get('login', function (){
return view('auth/login');
});
Route::get('register', function (){
if(Auth::check()){
return view('home');
}else{
return view('auth/register');
}
});
Route::get('/', function () {
if(Auth::check()){
return view('home');
}else{
return redirect('/login');
}
});
Route::get('/home', 'HomeController#index')->name('home');
But i am keep getting this error "Route [login] not defined." and i can't see the problem.

If I add Auth::routes() in a fresh laravel 7 installation shows this on artisan route:list:
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+--------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+--------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | api/user | | Closure | api,auth:api |
| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController#showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\LoginController#login | web,guest |
| | POST | logout | logout | App\Http\Controllers\Auth\LoginController#logout | web |
| | GET|HEAD | password/confirm | password.confirm | App\Http\Controllers\Auth\ConfirmPasswordController#showConfirmForm | web,auth |
| | POST | password/confirm | | App\Http\Controllers\Auth\ConfirmPasswordController#confirm | web,auth |
| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail | web |
| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController#showLinkRequestForm | web |
| | POST | password/reset | password.update | App\Http\Controllers\Auth\ResetPasswordController#reset | web |
| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController#showResetForm | web |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController#showRegistrationForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\RegisterController#register | web,guest |
+--------+----------+------------------------+------------------+------------------------------------------------------------------------+--------------+
You should then avoid defining the same routes again with a different implementation. Let Laravel doing the work for you.
As you can see, there are also already middlewares applied to these predefined routes. web in this scenario is not a middleware itself but a middleware group defined at app/Http/Kernel.php. Please see below for more info about middleware groups.
If you want to kind of "remove" the / -route from your project you can use a redirect route.
https://laravel.com/docs/7.x/routing#redirect-routes
So your route file should, after all, look like this:
Auth::routes();
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
});
// this will let laravel automatically redirect again if already logged in
Route::permanentRedirect('/', '/login');
Route::get('/home', 'HomeController#index')->name('home');
The automation which will redirect you towards the /home-route is an interaction between app/Http/Middleware/RedirectIfAuthenticated.php and app/Providers/RouteServiceProvider.php.
Within the latter, you have an attribute defining your HOME
/**
* The path to the "home" route for your application.
*
* #var string
*/
public const HOME = '/home';
If you have later more routes which should apply the auth()-middleware you have three ways to do that (or probably 4):
Please compare the following examples to this link:
https://laravel.com/docs/7.x/middleware#middleware-groups
As a general thing maybe a bit hard to see in the beginning, there is no difference between a controller route and those which use a closure function. The methods which can be used are the same for both implementations. Only the handling of the route within the application will be different.
For a single route which is needing a middleware, just add it to the end.
This is applicable for controller routes as well as for closure routes.
Route::get('/', function () {
//
})->middleware('web');
// ^^^^ is as possible as:
Route::get('/', 'Controller#Method')->middleware('web');
For multiple routes using the same middleware use the middleware method.
It is possible to use multiple middlewares assigned as parts of the array.
Route::middleware(['web', 'subscribed'])->group(function () {
//
});
If you still need more customization use the group()-method directly.
Here you can define not only middleware but also for example a prefix for all enclosed routes
Route::group(['middleware' => ['web'], 'prefix'=>'admin'], function () {
//
});
As the last option, you can add any middleware you want to either an existing middleware group or add your own middleware group within app/Http/Kernel.php?. But this will cause pretty strong integration hard to build an exception for if you want to go off track because everything within a middleware group is used all the time for every route this group is applied to.
Please do not mix Route groups with middleware groups as these are different things.
All of these examples were found in the docs for the 7th version, so they should be applicable also for your case.

Related

Laravel route doesn't work. localhost8000/{route}/create always be ignored

Laravel route doesn't work. localhost8000/{route}/create always be ignored.
the create() function of the controller doesn't seem to be called.
The browser tries to link to the same page or /home
How Should I fix and check this?
web.php
Route::resource('/debug', 'WorkerController')->except(['index'])->middleware('auth');
class WorkController extends Controller
{
public function create(WorkRequest $request)
{
Log::debug("This function never be called", "!!");
return view("a");
}
public function store(WorkRequest $request)
{
$schedules = DB::table('schedules')->get();
$request->date;
$request->hours;
$worker_id = strval($request->user()->id);
Log::debug('date=' . $request->date);
//omit
$registerred_schedules = DB::table('worker_schedules')->where('worker_id', $worker_id)->get();
return view('workers.create', ['schedules' => $registerred_schedules]);
}
}
| | POST | debug | debug.store | App\Http\Controllers\WorkController#store | web,auth |
| | GET|HEAD | debug/create | debug.create | App\Http\Controllers\WorkController#create | web,auth |
| | DELETE | debug/{debug} | debug.destroy | App\Http\Controllers\WorkController#destroy | web,auth |
| | PUT|PATCH | debug/{debug} | debug.update | App\Http\Controllers\WorkController#update | web,auth |
| | GET|HEAD | debug/{debug} | debug.show | App\Http\Controllers\WorkController#show | web,auth |
| | GET|HEAD | debug/{debug}/edit | debug.edit | App\Http\Controllers\WorkController#edit | web,auth |
In your case:
Route /debug point to WorkController#store and follow the POST method.
So when you access it via GET method you get an exception.
While debug/create point to WorkController#create and follow the GET method.
So /debug/create should load your form or view and /debug should store the form data.
The index method is missing from your controller otherwise it would have called as default on /debug and had a GET method.

Undefined variable: categories (View: resources\views\product\create.blade.php)

hi m trying to get categories in products/create page but it says: (View: \resources\views\product\create.blade.php) how to resolve it?
controller:
public function create(Request $request)
{
$categories = Category::with('category')->distinct()->get();
return view('product.create', compact('categories'));
}
blade file:
<select name="select">
#foreach($categories as $category)
<option value="{{ $id }}">{{ $title }}</option>
#endforeach
</select>
category model:
public function products()
{
return $this->belongsToMany(Product::class,'category_product');
}
product model:
public function categories()
{
return $this->belongsToMany(Category::class,'category_product');
}
these are routes:
| | | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController#showResetForm | web,guest |
| | POST | product | product.store | App\Http\Controllers\ProductController#store | web |
| | GET|HEAD | product | product.index | App\Http\Controllers\ProductController#index | web |
| | GET|HEAD | product/create | product.create | App\Http\Controllers\ProductController#create | web |
| | DELETE | product/{product} | product.destroy | App\Http\Controllers\ProductController#destroy | web |
| | GET|HEAD | product/{product} | product.show | App\Http\Controllers\ProductController#show | web |
| | PUT|PATCH | product/{product} | product.update | App\Http\Controllers\ProductController#update | web |
| | GET|HEAD | product/{product}/edit | product.edit | App\Http\Controllers\ProductController#edit | web |
| | POST | register | | App\Http\Controllers\Auth\RegisterController#register | web,guest |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController#showRegistrationForm | web,guest |
if you want to retrieve categories list you just need to change your code like this, that way you will get correct all categories existed
public function create(Request $request)
{
$categories = Category::distinct()->get(); // or Category::all();
return view('product.create', compact('categories'));
}
if you curious with your error, you dont need with , this method used if you want to retrieve with the relationship needed (eager loading)
based on your blade, you don't need that since you want retrieve the category lists

Laravel route view name declaration not showing up

I have created routes in routes/web.php.
Route::prefix('home')->group(function () {
Route::view('/', 'landing.index', ['name' => 'landing.home']);
Route::post('/', 'SignupController#signup');
Route::view('thank-you', 'landing.thank-you', ['name' => 'landing.thankyou']);
});
However, when calling php artisan route:list it shows me:
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+----------------+-------+----------------------------------------------------+-------------+
| | GET|HEAD | home | | Illuminate\Routing\ViewController | web |
| | POST | home | | App\Http\Controllers\SignupController#signup | web |
| | GET|HEAD | home/thank-you | | Illuminate\Routing\ViewController | web |
Also, the name is not being registered.
Try this:
Route::prefix('home')->group(function () {
Route::view('/', 'landing.index')->name('landing.home');
Route::post('/', 'SignupController#signup');
Route::view('thank-you', 'landing.thank-you')->name('landing.thankyou');
});
Hope it helps.

Why is my route in Laravel returning a 404 error?

So in my routes.php file I have this:
Route::get('contact', function() {
return view('contact');
});
When I go to domain.com/contact I get a return error. However when I put:
Route::get('/', function() {
return view('contact');
});
and go to domain.com the page appears. Any idea what could be causing this?
Full Routes file:
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('homeIndex');
});
Route::get('contact', function() {
return view('contact');
});
php artisan route:list returns:
+--------+----------+---------+------+---------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+---------+------+---------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | contact | | Closure | web |
+--------+----------+---------+------+---------+------------+
Ok so I fixed my issue. If anyone else has this issue make sure mod_rewrite is enabled on your server. You do this by going to the terminal and entering
a2enmod rewrite
then typing
service apache2 restart
It now works like a charm.

Only exposing certain auth routes in Laravel

In Laravel 5.2 authentication is made dead simple and one of the ways it makes authentication simpler is by adding all routes necessary for authentication through one method, this method is Route::auth().
Which is great, but what is the best way of only exposing the ones necessary for login and logout actions and not the registration ones, because I want to have one master login, which can make other accounts to admin the website. But I don't want 'users' in the normal sense.
Method 1.
Add routes in web.php file.
For example when your app need only login and logout routes
Route::get('login', 'Auth\AuthController#showLoginForm');
Route::post('login', 'Auth\AuthController#login');
Route::get('logout', 'Auth\AuthController#logout');
Method 2 - There is a better way.
Just use the Auth::routes() method and add additional parameters.
Same example - App needs just login and logout routes
Auth::routes(['register' => false, 'reset' => false])
You can add to routes.php without registration route of course.
// Authentication Routes...
//Login Routes...
Route::get('login','AdminAuth\AuthController#showLoginForm');
Route::post('login','AdminAuth\AuthController#login');
Route::get('logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('register', 'Auth\AuthController#showRegistrationForm');
// Password Reset Routes...
Route::get('password/reset/{token?}','Auth\PasswordController#showResetForm');
If you run have the Route::auth() method in your routes.php and run the php artisan route:list command you can see which routes it defines.
In this case they're:
+--------+----------+-------------------------+------+---------------------- -------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+------------+
| | GET|HEAD | / | | Closure | web |
| | GET|HEAD | home | | App\Http\Controllers\HomeController#index | web,auth |
| | GET|HEAD | login | | App\Http\Controllers\Auth\AuthController#showLoginForm | web,guest |
| | POST | login | | App\Http\Controllers\Auth\AuthController#login | web,guest |
| | GET|HEAD | logout | | App\Http\Controllers\Auth\AuthController#logout | web |
| | POST | password/email | | App\Http\Controllers\Auth\PasswordController#sendResetLinkEmail | web,guest |
| | POST | password/reset | | App\Http\Controllers\Auth\PasswordController#reset | web,guest |
| | GET|HEAD | password/reset/{token?} | | App\Http\Controllers\Auth\PasswordController#showResetForm | web,guest |
| | GET|HEAD | register | | App\Http\Controllers\Auth\AuthController#showRegistrationForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\AuthController#register | web,guest |
+--------+----------+-------------------------+------+-----------------------------------------------------------------+------------+
You can clearly see which are necessary in the URI colum; login (get), login (post) and logout (get).
Remove the Route::auth() method from routes.php and add the following:
Route::get('login', 'Auth\AuthController#showLoginForm');
Route::post('login', 'Auth\AuthController#login');
Route::get('logout', 'Auth\AuthController#logout');
If you do want the already registered admins to be able to manually change their password you would also include those:
Route::post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController#reset');
Route::get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
Don't forget the tools given to you :)

Resources