PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-routing. Show all posts
Showing posts with label laravel-routing. Show all posts

Tuesday, November 15, 2022

[FIXED] How to extend Laravel's basic route resource in Laravel 6?

 November 15, 2022     laravel, laravel-6, laravel-routing     No comments   

Issue

I'm using Laravel as an API with many endpoints and many controllers. I'm using Route::resource() method to define REST endpoints, but in most cases I need to add one more endpoint and now my code is looking like this:

Route::get('product/list', 'ProductController@all');
Route::resource('product', 'ProductController');

Route::get('property/list', 'PropertyController@all');
Route::resource('property', 'PropertyController');

Route::get('customer/list', 'CustomerController@all');
Route::resource('customer', 'CustomerController');

...and this sample keeps coming up, over and over again. I think there needs to be a practical and better way to define this {resource}/list URI in one place. Now I need to repeat this sample:

Route::get('{resource}/list', 'NameOfController@all');

Is there a better solution to define this endpoint only once and be available in every controllers? Can I avoid somehow the repetition?


Solution

If you take a look at the resource method in the Illuminate\Routing\Router class, you are going to see this:

if ($this->container && $this->container->bound(ResourceRegistrar::class)) {
    $registrar = $this->container->make(ResourceRegistrar::class);
} else {
    $registrar = new ResourceRegistrar($this);
}

Which means you can bind a ResourceRegistrar to overwrite the default one provided by Laravel. Therefore, to achieve what you want, you could first make a new class, for instance, app/ResourceRegistrar.php, which would extends the Illuminate\Routing\ResourceRegistrar and add a default 'list':

<?php

namespace App;

use Illuminate\Routing\ResourceRegistrar as BaseResourceRegistrar;

class ResourceRegistrar extends BaseResourceRegistrar
{
    protected $resourceDefaults = [
        'index', 'create', 'store', 'show', 'edit', 'update', 'destroy', 'list',
    ];

    /**
     * Add the list method for a resourceful route.
     *
     * @param  string  $name
     * @param  string  $base
     * @param  string  $controller
     * @param  array   $options
     * @return \Illuminate\Routing\Route
     */
    public function addResourceList($name, $base, $controller, $options)
    {
        $uri = $this->getResourceUri($name).'/all';

        $action = $this->getResourceAction($name, $controller, 'list', $options);

        return $this->router->get($uri, $action);
    }
}

And then, you can simply bind the registrar in your AppServiceProvider:

<?php

namespace App\Providers;

use App\ResourceRegistrar;
use Illuminate\Routing\Router;
use Illuminate\Routing\ResourceRegistrar as BaseResourceRegistrar;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->app->bind(BaseResourceRegistrar::class, ResourceRegistrar::class);
    }
}

And you can register your route like you used to without adding the extra line:

Route::resource('product', 'ProductController');
Route::resource('property', 'PropertyController');
Route::resource('customer', 'CustomerController');

Then if you run the php artisan route:list, you should see the {resource}/list route.



Answered By - Chin Leung
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, April 18, 2022

[FIXED] How to clear Laravel route caching on server

 April 18, 2022     laravel, laravel-routing     No comments   

Issue

This is regarding route cache on localhost

About Localhost

I have 2 routes in my route.php file. Both are working fine. No problem in that. I was learning route:clear and route:cache and found a small problem below.

if I comment any one route in my route.php file and then run below command

php artisan route:cache

This will keep the route disabled because the route list is in cache now. Now, go to route.php file and try to remove commented route and then try to run that enabled url. still it will show 404 because I need to remove cache by using below command

php artisan route:clear

So far everything is understood in localhost. No problem in that.

After deploying on shared hosting server on godaddy

Question : How can I remove the route cache on server?


Solution

If you want to remove the routes cache on your server, remove this file:

bootstrap/cache/routes.php

And if you want to update it just run php artisan route:cache and upload the bootstrap/cache/routes.php to your server.



Answered By - Dees Oomens
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, March 11, 2022

[FIXED] Laravel: How to Get Current Route Name? (v5 ... v7)

 March 11, 2022     laravel, laravel-5, laravel-6, laravel-routing, php     No comments   

Issue

In Laravel v4 I was able to get the current route name using...

Route::currentRouteName()

How can I do it in Laravel v5 and Laravel v6?


Solution

Try this

Route::getCurrentRoute()->getPath();

or

\Request::route()->getName()

from v5.1

use Illuminate\Support\Facades\Route;
$currentPath= Route::getFacadeRoot()->current()->uri();

Laravel v5.2

Route::currentRouteName(); //use Illuminate\Support\Facades\Route;

Or if you need the action name

Route::getCurrentRoute()->getActionName();

Laravel 5.2 route documentation

Retrieving The Request URI

The path method returns the request's URI. So, if the incoming request is targeted at http://example.com/foo/bar, the path method will return foo/bar:

$uri = $request->path();

The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method:

if ($request->is('admin/*')) {
    //
}

To get the full URL, not just the path info, you may use the url method on the request instance:

$url = $request->url();

Laravel v5.3 ... v5.8

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

Laravel 5.3 route documentation

Laravel v6.x...7.x

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

** Current as of Nov 11th 2019 - version 6.5 **

Laravel 6.x route documentation

There is an option to use request to get route

$request->route()->getName();


Answered By - Adnan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 2, 2022

[FIXED] How to use the request route parameter in Laravel 5 form request?

 March 02, 2022     laravel, laravel-5, laravel-routing, laravel-validation, php     No comments   

Issue

I am new to Laravel 5 and I am trying to use the new Form Request to validate all forms in my application.

Now I am stuck at a point where I need to DELETE a resource and I created a DeleteResourceRequest for just to use the authorize method.

The problem is that I need to find what id is being requested in the route parameter but I cannot see how to get that in to the authorize method.

I can use the id in the controller method like so:

public function destroy($id, DeletePivotRequest $request)
{
    Resource::findOrFail($id);
}

But how to get this to work in the authorize method of the Form Request?


Solution

That's very simple, just use the route() method. Assuming your route parameter is called id:

public function authorize(){
    $id = $this->route('id');
}


Answered By - lukasgeiter
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 26, 2022

[FIXED] how can i set url of route from AJAX

 February 26, 2022     ajax, laravel, laravel-routing     No comments   

Issue

WEB (route) :

Route::get('/ajax-cat/edit/{id}', [App\Http\Controllers\AjaxCRUDController::class, 'categoryEdit'])->name('ajax.categoryEdit');

AJAX Code:

    $(document).ready(function () {
    $("#categoryBtn").click(function () {
        $("#catTable").show();
        let html = '';
        let i = 0;
        $.ajax({
            url: '/ajax-cat',
            type: "GET",
            success: function (data) {
                for (const x of data) {
                    html += `<tr>
                                <th scope="row">${++i}</th>
                                <td>${x.name}</td>
                                <td><a href="{{route('ajax.categoryEdit',${x.id})}}" class="btn btn-danger">Edit</a></td>
                            </tr>`;
                }
                $("#catTableBody").html(html);
            }
        });

    });
});

Picture from Browser:

enter image description here

But I want Link like this: 127.0.0.1:8000/ajax-cat/edit/2


Solution

You cannot merge different language syntax like this.

{{ }} is from Blade Directive. https://laravel.com/docs/8.x/blade

x.id

is a variable defined in your javascript code block.

What you can do is:

var url = '{{route("ajax.categoryEdit", ":id")}}';
url = url.replace(':id', x.id);

Then you can concat your javascript variable inside your html code.



Answered By - calebe santana
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to change route URL in Laravel 9 resource controller

 February 26, 2022     laravel, laravel-9, laravel-routing     No comments   

Issue

I wondered if there is a way to change the default URLs of Laravel's resource controller. For example, for basic CRUD operation, for creating, we have a /create route made by default by Laravel. Can it be changed to /ask or /new or something like that?


Solution

You can "localize" the resource URIs that are created without much work (Added to the boot method of a Service Provider):

Route::resourceVerbs([
    'create' => 'new',
]);

This would have all calls to Route::resource(...) create the URI with 'new' instead of 'create' for the create action.

If you need to get more complicated than something like that you could extend Illuminate\Routing\ResourceRegistrar to override it in any way you would like. You could call an instance of your version or bind it to the container for Illuminate\Routing\ResourceRegistrar which would use it for all resource calls.

Laravel 9.x - Docs - Controllers - Resource Controllers - Localizing Resource URIs



Answered By - lagbox
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 21, 2022

[FIXED] Unable to prepare route [password/reset] for serialization. Another route has already been assigned name [password.request]

 February 21, 2022     laravel, laravel-routing     No comments   

Issue

I have created a small application in Laravel 8. Everything is fine, but when I wanted to configure the cache I had an error that one route has the same name as another.

Reviewing the routes I found duplicate named routes, but since I'm new to Laravel, I don't know how to solve this problem. I do not know what to do to have two routes with the same name I hope you can guide me a bit.

Screenshot output of php artisan route:list


Solution

Just override the laravel auth routes

Route::post('password/email', [
    'as' => 'laravel.password.email',
    'uses' => 'App\Http\Controllers\Auth\ForgotPasswordController@sendResetLinkEmail'
]);

Route::get('password/reset', [
    'as' => 'laravel.password.request',
    'uses' => 'App\Http\Controllers\Auth\ForgotPasswordController@showLinkRequestForm'
]);

But dont forget to change the old route names



Answered By - ibra
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 20, 2022

[FIXED] Laravel 5 Resourceful Routes Plus Middleware

 February 20, 2022     laravel, laravel-5, laravel-middleware, laravel-routing, routes     No comments   

Issue

Is it possible to add middleware to all or some items of a resourceful route?

For example...

<?php

Route::resource('quotes', 'QuotesController');

Furthermore, if possible, I wanted to make all routes aside from index and show use the auth middleware. Or would this be something that needs to be done within the controller?


Solution

In QuotesController constructor you can then use:

$this->middleware('auth', ['except' => ['index','show']]);

Reference: Controller middleware in Laravel 5



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 19, 2022

[FIXED] How to put route in anchor tag in laravel 5.2

 February 19, 2022     laravel-5.2, laravel-routing     No comments   

Issue

I've gone through many of the articles below, which explains generating link from named route, but unable to solve my problem.

Tutorial 1

Tutorial 2

Tutorial 3

Following is the defined routes:

Route::get('/nitsadmin/dashboard', function () {
    return view('nitsadmin.dashboard');
});

And I'm calling link in anchor tag:

<a id="index" class="navbar-brand" href="{{Html::linkRoute('/nitsadmin/dashboard')}}">
      <img src="../img/admin/nitseditorlogo.png" alt="Logo">
</a>

I'm getting following error:

enter image description here


Solution

You can do this quite simply with the url() helper.

Just replace your anchor tag like so:

<a id="index" class="navbar-brand" href="{{url('/nitsadmin/dashboard')}}">
      <img src="../img/admin/nitseditorlogo.png" alt="Logo">
</a>

Regarding the image that you have used in there, if these were to be stored in your public folder then you could always use the asset() helper. This would help you turn your absolute links to in dynamic ones.



Answered By - James
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, February 16, 2022

[FIXED] Laravel URL Filtering with GET

 February 16, 2022     laravel, laravel-request, laravel-routing, php, routes     No comments   

Issue

I am building a simple Laravel routing to display an array when someone goes to http://127.0.0.1:8000/planets

But I need to make a filter to check the array on what request has been send on the URL. For example: http://127.0.0.1:8000/planets?planet=mars

I need to make sure that if a GET parameter is present, you filter the array based on whether the planet name is in it. This way we can filter the results of the page a little faster.

The code I currently have Web.php:

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/planets', function () {
    
    $planets = [
        [
            'name' => 'Mars',
            'description' => 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury.'
        ],
        [
            'name' => 'Venus',
            'description' => 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
        ],
        [
            'name' => 'Earth',
            'description' => 'Our home planet is the third planet from the Sun, and the only place we know of so far thats inhabited by living things.'
        ]
    ];
    
    return view('welcome', ['planets'=>$planets]);
});

And my welcome blade:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">

        <style>
            html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent}[hidden]{display:none}html{font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;line-height:1.5}*,:after,:before{box-sizing:border-box;border:0 solid #e2e8f0}a{color:inherit;text-decoration:inherit}svg,video{display:block;vertical-align:middle}video{max-width:100%;height:auto}.bg-white{--bg-opacity:1;background-color:#fff;background-color:rgba(255,255,255,var(--bg-opacity))}.bg-gray-100{--bg-opacity:1;background-color:#f7fafc;background-color:rgba(247,250,252,var(--bg-opacity))}.border-gray-200{--border-opacity:1;border-color:#edf2f7;border-color:rgba(237,242,247,var(--border-opacity))}.border-t{border-top-width:1px}.flex{display:flex}.grid{display:grid}.hidden{display:none}.items-center{align-items:center}.justify-center{justify-content:center}.font-semibold{font-weight:600}.h-5{height:1.25rem}.h-8{height:2rem}.h-16{height:4rem}.text-sm{font-size:.875rem}.text-lg{font-size:1.125rem}.leading-7{line-height:1.75rem}.mx-auto{margin-left:auto;margin-right:auto}.ml-1{margin-left:.25rem}.mt-2{margin-top:.5rem}.mr-2{margin-right:.5rem}.ml-2{margin-left:.5rem}.mt-4{margin-top:1rem}.ml-4{margin-left:1rem}.mt-8{margin-top:2rem}.ml-12{margin-left:3rem}.-mt-px{margin-top:-1px}.max-w-6xl{max-width:72rem}.min-h-screen{min-height:100vh}.overflow-hidden{overflow:hidden}.p-6{padding:1.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.pt-8{padding-top:2rem}.fixed{position:fixed}.relative{position:relative}.top-0{top:0}.right-0{right:0}.shadow{box-shadow:0 1px 3px 0 rgba(0,0,0,.1),0 1px 2px 0 rgba(0,0,0,.06)}.text-center{text-align:center}.text-gray-200{--text-opacity:1;color:#edf2f7;color:rgba(237,242,247,var(--text-opacity))}.text-gray-300{--text-opacity:1;color:#e2e8f0;color:rgba(226,232,240,var(--text-opacity))}.text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.text-gray-500{--text-opacity:1;color:#a0aec0;color:rgba(160,174,192,var(--text-opacity))}.text-gray-600{--text-opacity:1;color:#718096;color:rgba(113,128,150,var(--text-opacity))}.text-gray-700{--text-opacity:1;color:#4a5568;color:rgba(74,85,104,var(--text-opacity))}.text-gray-900{--text-opacity:1;color:#1a202c;color:rgba(26,32,44,var(--text-opacity))}.underline{text-decoration:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.w-5{width:1.25rem}.w-8{width:2rem}.w-auto{width:auto}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}@media (min-width:640px){.sm\:rounded-lg{border-radius:.5rem}.sm\:block{display:block}.sm\:items-center{align-items:center}.sm\:justify-start{justify-content:flex-start}.sm\:justify-between{justify-content:space-between}.sm\:h-20{height:5rem}.sm\:ml-0{margin-left:0}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:pt-0{padding-top:0}.sm\:text-left{text-align:left}.sm\:text-right{text-align:right}}@media (min-width:768px){.md\:border-t-0{border-top-width:0}.md\:border-l{border-left-width:1px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:1024px){.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:bg-gray-800{--bg-opacity:1;background-color:#2d3748;background-color:rgba(45,55,72,var(--bg-opacity))}.dark\:bg-gray-900{--bg-opacity:1;background-color:#1a202c;background-color:rgba(26,32,44,var(--bg-opacity))}.dark\:border-gray-700{--border-opacity:1;border-color:#4a5568;border-color:rgba(74,85,104,var(--border-opacity))}.dark\:text-white{--text-opacity:1;color:#fff;color:rgba(255,255,255,var(--text-opacity))}.dark\:text-gray-400{--text-opacity:1;color:#cbd5e0;color:rgba(203,213,224,var(--text-opacity))}.dark\:text-gray-500{--tw-text-opacity:1;color:#6b7280;color:rgba(107,114,128,var(--tw-text-opacity))}}
        </style>

        <style>
            body {
                font-family: 'Nunito', sans-serif;
                font-weight: bolder;
            }
        </style>
    </head>
    <body class="antialiased">

@foreach ($planets as $planet)
    <ul>
        <li>{{$planet['name']}}</li>
        <p>{{$planet['description']}}</p>
    </ul>
@endforeach
    
    </body>
</html>

Solution

The Laravel Illuminate\Http\Request object has a query method on it that allows you access to query string parameters.

$request->query('param');

So for your scenario and given the URL example.com/planets?names=mars,earth, you would grab the planet names as follows:

$names = $request->query('names');

That would result in the $names variable having the string value mars,earth.

From here you want to use explode to separate out the individual names:

$names = explode(',', $request->query('names');

This time $names is an array with two elements, mars and earth.

Then you can use the whereIn method available on Laravel Collections to filter your planets to just those found in the $names array.

$planets = collect($planets)
    ->whereIn('name', array_map(fn($name) => strtolower($name), $names))
    ->all();

Note that for the above to work I have done two things.

  1. I made all the planet names in your $planets array lower case
  2. I use array_map to convert the query parameter values to lower case for comparing with the $planets array

This should mitigate casing issues (so people typing mars, MARS or other variations) should be captured correctly.

Put it all together and you should have something like the following:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/planets', function (Request $request) {

    $planets = [
        [
            'name' => 'mars',
            'description' => 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury.'
        ],
        [
            'name' => 'venus',
            'description' => 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
        ],
        [
            'name' => 'earth',
            'description' => 'Our home planet is the third planet from the Sun, and the only place we know of so far thats inhabited by living things.'
        ]
    ];

    if ($request->query('names')) {
        $names = explode(',', $request->query('names'));
        $planets = collect($planets)->whereIn('name', array_map(fn($name) => strtolower($name), $names))->all();
    }

    return view('welcome', compact('planets'));
});


Answered By - Peppermintology
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 22, 2022

[FIXED] How to get a list of registered route paths in Laravel?

 January 22, 2022     arrays, laravel, laravel-4, laravel-routing     No comments   

Issue

I was hoping to find a way to create an array with the registered routes paths within Laravel 4.

Essentially, I am looking to get a list something like this returned:

/
/login
/join
/password

I did come across a method Route::getRoutes() which returns an object with the routes information as well as the resources but the path information is protected and I don't have direct access to the information.

Is there any other way to achieve this? Perhaps a different method?


Solution

Route::getRoutes() returns a RouteCollection. On each element, you can do a simple $route->getPath() to get path of the current route.

Each protected parameter can be get with a standard getter.

Looping works like this:

$routeCollection = Illuminate\Support\Facades\Route::getRoutes();

foreach ($routeCollection as $value) {
    echo $value->getPath();
}


Answered By - netvision73
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 15, 2022

[FIXED] How to add a default parameter for all routes in laravel

 January 15, 2022     laravel, laravel-localization, laravel-routing, localization, php     No comments   

Issue

I have a multi lingual website. where i want to add current locale as prefix for all of my project routes. For that to be than any time i use a route i must always provide a value for locale parameter of the route. I think there are better ways of doing this.

My routes looks like this

Route::prefix('{locale}')->group(function() {
    Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
    Route::get('/blog', [App\Http\Controllers\PostController::class, 'index'])->name('blog');
});

I want my path in url looks like this.

  • http://localhost/project/en/blog or
  • http://localhost/project/fa/blog

I also have a middleware SetLocale where I decide app locale according to the request path coming through;

here is my middleware code

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {

        $locale = $request->segment(1);
        if (! is_null($locale) && ! in_array($locale, config('app.locales')) ) // config('app.locales') = ['en', 'ar', 'fa']
            abort(404);

        $html_dir = in_array($locale, ['en'])?'ltr':'rtl';
        \Illuminate\Support\Facades\Config::set('app.html_dir', $html_dir);
        \Illuminate\Support\Facades\App::setLocale($locale);


        return $next($request);
    }
}

Solution

You can use the defaults method of the URL Generator do this exact thing:

URL::defaults(['locale' => $locale]);

Add that in your middleware and the locale parameter will have a default when generating a URL to routes using that parameter.

Laravel 8.x Docs - URL Generation - Default Values defaults



Answered By - lagbox
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 8, 2022

[FIXED] How to use old Laravel routing style in Laravel 8

 January 08, 2022     laravel, laravel-5, laravel-8, laravel-routing     No comments   

Issue

I just installed Laravel 8 and in this version, I have to type my routes like this:

Route::get('/admin/panel', [App\Http\Controllers\Admin\PanelController::class, 'index']);

But I got used to Laravel 5 routes which looked like this:

Route::namespace('Admin')->prefix('admin')->group(function () {
    Route::get('/panel', 'Admin/PanelController@index');
});

So how can I use this Laravel 5 routing inside Laravel 8 version?


Solution

You can still use it to some extend (e.g. grouping and prefixing a route) but because you're using a FQCN the namespace is redundant. The major advantage using the "new" routing over of the "old" one is refactoring. When you move or rename your controller with an IDE that supports refactoring like PhpStorm you wouldn't need to manually change the name and group namespace of your controller.

In Laravel 5 you were able to use this route notation too but it wasn't outlined in the documentation.

To achieve a similar feeling, import the namespace and use just your class names and get rid of the namespace-group in the definition.

use App\Http\Controllers\Admin\PanelController;

Route::prefix('admin')->group(function () {
    Route::get('panel', [PanelController::class, 'index']);
});

If you just cannot live with the new way of defining routes, uncomment the $namespace property in app/Providers/RouteServiceProvider.php and you're back to the old way.



Answered By - Dan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 3, 2022

[FIXED] Make session expiration redirect back to login?

 January 03, 2022     laravel, laravel-4, laravel-5, laravel-5.1, laravel-routing     No comments   

Issue

When user logs in and is authenticated, I use Auth::user()->username; to show username of user on dashboard. However, for some reason when session expires the class Auth doesn't seem to work and dashboard page throws error as trying to get property of non-object for Auth::user()->username;. How can I redirect the user back to the login page when he clicks any link or refreshes the page after the session has expired?

I tried the Authenticate.php middleware but it always redirects back to login page,whatever you put the credentials either correct or incorrect.However,when I don't use this middleware it logins the user.Am I missing something?

Route.php

    <?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.
|
*/

/*
Actions Handled By Resource Controller

Verb        Path                    Action      Route Name
GET         /photo                  index       photo.index
GET         /photo/create           create      photo.create
POST        /photo                  store       photo.store
GET         /photo/{photo}          show        photo.show
GET         /photo/{photo}/edit     edit        photo.edit
PUT/PATCH   /photo/{photo}          update      photo.update
DELETE      /photo/{photo}          destroy     photo.destroy


Adding Additional Routes To Resource Controllers

If it becomes necessary to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:

Route::get('photos/popular', 'PhotoController@method');

Route::resource('photos', 'PhotoController');

*/

// Display all SQL executed in Eloquent
// Event::listen('illuminate.query', function($query)
// {
//     var_dump($query);
// });



define('ADMIN','admin');
define('SITE','site');


Route::group(['namespace' => ADMIN], function () {
    Route::get('/','UserController@showLogin'); 
});


////////////////////////////////////Routes for backend///////////////////////////////////////////////////
Route::group(['prefix' => ADMIN,'middleware' => 'auth'], function () {
    Route::group(['namespace' => ADMIN], function () {
    //Route::get('/','EshopController@products');

        //sumit routes for user registration
        //Route::resource('users','UserController');
        Route::get('/users/destroy/{id}','UserController@destroy');
        Route::get('UserProf','UserController@userProf');
        Route::get('users','UserController@index');
        Route::get('/users/create','UserController@create');
        Route::get('/users/adminEdit/{id}','UserController@adminEdit');
        Route::post('/users/adminUpdate','UserController@adminUpdate');
        Route::post('/users/store','UserController@store');
        Route::get('/users/edit/{id}','UserController@edit');
        Route::post('/users/update/{id}','UserController@update');

        //airlines route
        Route::get('airlines','AirlinesController@index');
        Route::get('/airlines/create','AirlinesController@create');
        Route::post('/airlines/store','AirlinesController@store');
        Route::get('/airlines/edit/{id}','AirlinesController@edit');
        Route::post('/airlines/update','AirlinesController@update');
        Route::get('/airlines/destroy/{id}','AirlinesController@destroy');
        //end sumit routes

        //flight routes
        Route::get('flights','FlightController@index');
        Route::get('showFlightBook','FlightController@showFlightBook');
        Route::get('flights/create','FlightController@create');
        Route::post('flights/store','FlightController@store');
        Route::get('flights/book','FlightController@book');
        Route::get('flights/edit/{id}','FlightController@edit');
        Route::post('flights/update','FlightController@update');
        Route::get('flights/destroy/{id}','FlightController@destroy');

        //Route::resource('flight','FlightController');

        //hotels route
        Route::get('hotels','HotelsController@index');
        Route::get('/hotels/create','HotelsController@create');
        Route::post('/hotels/store','HotelsController@store');
        Route::get('/hotels/edit/{id}','HotelsController@edit');
        Route::post('/hotels/update','HotelsController@update');
        Route::get('/hotels/destroy/{id}','HotelsController@destroy');
        //end sumit routes

        //book-hotel routes
        Route::get('hotel-book','HotelBookController@index');
        Route::get('showHotelBook','HotelBookController@showHotelBook');
        Route::get('hotel-book/create','HotelBookController@create');
        Route::post('hotel-book/store','HotelBookController@store');
        Route::get('hotel-book/book','HotelBookController@book');
        Route::get('hotel-book/edit/{id}','HotelBookController@edit');
        Route::post('hotel-book/update','HotelBookController@update');
        Route::get('hotel-book/destroy/{id}','HotelBookController@destroy');


        //Route::resource('hotel','HotelController');
        //close flight routes


        //for admin login
        //Route::get('initlogin','UserController@lgnPage');
        Route::get('login','UserController@showLogin');
        // Route::get('privilegeLogin','UserController@privilegeLogin');
        // Route::post('privilegeCheck','UserController@privilegeCheck');
        Route::post('login','UserController@doLogin');
        Route::get('/dashboard','DashController@index');
        Route::get('logout','UserController@doLogout');
        //user login 
        //Route::get('userLogin','UserController@showUserLogin');
        //Route::post('userLogin','UserController@doUserLogin');
        Route::get('/userDashboard','DashController@userIndex');
        Route::get('Logout','UserController@doUserLogout');
        //password reset
        Route::get('forget-pass','UserController@showReset');
        //Route::get('home', 'PassResetEmailController@index');






  });   
});

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

Authenticate.php:

    <?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate {

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                // return redirect()->guest('auth/login');
                return redirect()->guest('/');
            }
        }

        return $next($request);
    }

}

Solution

If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class. So, to protect every route from being accessed without authentication do this

protected $middleware = [
        'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
        'Illuminate\Cookie\Middleware\EncryptCookies',
        'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
        'Illuminate\Session\Middleware\StartSession',
        'Illuminate\View\Middleware\ShareErrorsFromSession',
        'App\Http\Middleware\VerifyCsrfToken',
        'App\Http\Middleware\Authenticate',// add this line according to your namespace
    ];

it will redirect the user if not logged in. UPDATE Keep in mind that adding auth middleware as global will create redirect loop so avoid it.

Or if you want specific routes to be protected then attach the middleware auth to that route

Route::get('admin/profile', ['middleware' => 'auth', function () {
    //
}]);

I think you are not attaching the auth middleware to your routes.



Answered By - Chaudhry Waqas
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, December 28, 2021

[FIXED] Basic routing generates a 404 in Laravel

 December 28, 2021     laravel, laravel-routing, mamp, url-routing     No comments   

Issue

I'm trying to use the Laravel framework in building my application. However, I'm getting stuck with routing.

Route

Route::get('ecatalogs', 
    array('as' => 'ecatalog_latest', 'uses' => 'ecatalogs@latest'));

Controller

class Catalogs_Controller extends Base_Controller
{
    public $restful = true;

    public function get_latest()
    {
        return "wohoooooo!";
    }
}

My localhost files are stored in /Users/ariefbayu/Sites/ and my Laravel application is stored in /Users/ariefbayu/Sites/ecatalog/. Inside this directory, I have an info.php file to confirm if my path settings are working, and they do. However, when I navigate to http://localhost/ecatalog/public/index.php/ecatalogs it always returns a 404 error. I know this is basic, but I don't know why this doesn't work.

FYI, I'm using a MAMP server, and I've set all source files' access permissions to 777 to test if this is a permission problem.


Solution

Route::get('ecatalogs', array('as'=>'ecatalog_latest', 'uses'=>'ecatalogs@latest'));

Notice the ecatalogs@latest pointer. This tells Laravel to call the get_latest() method on the Ecatalog_Controller.

And this is your controller Catalogs_Controller and function get_latest(). You need to call the get_latest() with this :

Route::get('ecatalogs', array('as'=>'ecatalog_latest', 'uses'=>'catalogs@latest'));


Answered By - Wahyu Kristianto
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing