#GET route that gets values from a Middleware

48 messages · Page 1 of 1 (latest)

violet basalt
#

Why are you doing this in a middleware? If you have some sort of CMS that has pages with custom paths, just create a “catch all” route that looks up the page based on the path, and then renders that page in a template:

Route::get('/{path}', DynamicPageController::class)->where('path', '.*');
class DynamicPageController extends Controller
{
    public function __invoke(string $path)
    {
        // Look up page based on $path...
        $page = someMethodToFindPage($path);

        // If there is no match, return a 404 Not Found error
        abort_unless($page, 404);

        // Render page model in a Blade template
        return view('page.show', compact('page'));
    }
}
vestal harbor
#

just for curiosity

#

when should i go for the middleware ?

violet basalt
#

When you need to manipulate a request or a response for whatever reason.

#

So authentication is middleware because you want to check there’s an authenticated user before the request is passed to a controller for handling.

#

The middleware can then intercept the request and return an appropriate response (401 Unauthorized, or redirect to login page) if a user is not authenticated.

#

Because you don’t want a request reaching a controller if the request requires authentication but there isn’t actually a user authenticated.

vestal harbor
#

Undefined function 'App\Http\Controllers\findPath'.

#

@violet basalt

#

why do i get this error when i call a function inside the same controller

violet basalt
#

Because you’re trying to call a method that doesn’t actually exist.

vestal harbor
#

how come ?

violet basalt
#

I don’t know. Why are you trying to call a method that doesn’t exist? 🤷‍♂️

#

Only you can answer that question, buddy.

vestal harbor
#
public function findPath($path)
    {
        $menuPage = DB::table('menu as m')
        ->select('m.id', 'm.name', 'p.content', 'm.template', 'm.active', 'm.hierarchy_path')
        ->join('pages as p', 'm.id', '=', 'p.id')
        ->where('m.id', '=', function($query) use ($path) {
            $query->select('id')
                ->from('menu')
                ->where('hierarchy_path', '=', $path)
                ->where('lang', '=', 'pt');
        })
        ->get();

        return $menuPage;
    }```
#

this is the method so i believe it exists

violet basalt
#

But where is that method? Because it’s clearly not in the controller you’re trying to call it from.

vestal harbor
#
class DynamicPageController extends Controller
{
    public function __invoke(string $path)
    {

        $page = findPath($path);

        // If there is no match, return a 404 Not Found error
        abort_unless($page, 404);

        // Render page model in a Blade template
        return view('page.show', compact('page'));
    }

    public function findPath($path)
    {
        $menuPage = DB::table('menu as m')
        ->select('m.id', 'm.name', 'p.content', 'm.template', 'm.active', 'm.hierarchy_path')
        ->join('pages as p', 'm.id', '=', 'p.id')
        ->where('m.id', '=', function($query) use ($path) {
            $query->select('id')
                ->from('menu')
                ->where('hierarchy_path', '=', $path)
                ->where('lang', '=', 'pt');
        })
        ->get();

        return $menuPage;
    }

}```
violet basalt
#

Because your syntax is wrong.

#
$page = $this->findPath($path);
vestal harbor
#

oh ok

violet basalt
#

You should also be using ->first() instead of ->get() if you’re only expecting one result.

#

->get() will return a collection, no matter how many matches there are.

#

Or even better, use ->firstOrFail(), which will automatically throw a 404 error if there are no results.

vestal harbor
#

thanks

vestal harbor
#

im sorry for being annoying

#

they gave me this job without even time to study this framework

violet basalt
#

What version of Laravel are you using?
Run php artisan --version

vestal harbor
#

9

#

9.52 i belive

violet basalt
#

What does your RouteServiceProvider file look like?

violet basalt
vestal harbor
#
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}
violet basalt
#

I just want to see if the routes are expecting namespaces or not.

vestal harbor
#
<?php

use Illuminate\Support\Facades\Route;
#

im only using route

#

the other ones are unused

violet basalt
#

I wanted to see a couple of your actual routes so I could see if there were expecting namespaces or not.

vestal harbor
#

i solved it!

#

[DynamicPageController::class]

#

the square brackets on the route

#

were missing

vestal harbor
#

i simply get this

#

found that the solution was to remove squarebrackets fro mthe route but now im back on the old error