LoveTheBlues's avatar

Pls help: Route not working?

Please be kind; I am new to Laravel. The issue I am facing is:

Some "broken images" on the webpage, and when inspecting the element it shows: '<' img src="/getDefaultAvatar?item=2431&name=xxxx&size=40" alt="user" class="rounded-circle mr-2" style="width: 40px; height: 40px;" '>' (single quotes added around the angle brackets otherwise you cant see the HTML tag)

In the code, "getDefaultAvatar" is set as a route in \routes\web.php as follows: Route::get('/getDefaultAvatar', 'DefaultAvatarController@make');

And class DefaultAvatarController is defined As follows in app\Http\Controllers\Web\DefaultAvatarController.php: class DefaultAvatarController extends Controller, is in namespace App\Http\Controllers\Web;, and has a public function make()

Can anyone suggest why the getDefaultAvatar is not being treated as a route and generating a link to a real image

UPDATE: Thanks for all your help. I fixed the problem and also along the way (with the hints and suggestions from various responses here) fixed a bunch of other issues with other routes that would have probably manifested as issues later. The issue turned out to be that route was calling a controller that called the php function file_exists() with an argument being a file in a restricted folder. It seems that different versions of PHP treat that differently (or perhaps different configs of hosting server). i.e. 500 error vs running ok but returning false. The manual says it should throw a non-fatal E_WARNING but continue running.

0 likes
28 replies
shadkamel's avatar

hi, can you show me the code in make function and the HTML code please ?

LoveTheBlues's avatar

@shadkamel The make function looks as follows:

public function make(Request $request)
{
    $this->handleInputs($request);
    $avatar = new InitialAvatar();

    $image = $avatar->name($this->name)
        ->length($this->length)
        ->fontSize($this->fontSize)
        ->size($this->size)
        ->background($this->background)
        ->color($this->color)
        ->smooth()
        ->allowSpecialCharacters(false)
        ->autoFont()
        ->keepCase(!$this->uppercase)
        ->rounded($this->rounded);

    $image = $image->generate();

    return $image->response('png', 100);
 }

In terms of the HTML, do you mean the source code file or what the browser is getting (i.e. what the browser shows when I hit "show source")?

LoveTheBlues's avatar

@shadkamel

One thing I just noticed:

That make function for class DefaultAvatarController in the file DefaultAvatarController.php has the following use statement: use LasseRafn\InitialAvatarGenerator\InitialAvatar;

But there is no folder "LasseRafn\InitialAvatarGenerator"

Instead, there is the following folder containing a file InitialAvatar.php vendor\lasserafn\php-initial-avatar-generator\src

Could that explain anything?

LoveTheBlues's avatar

@shadkamel Thanks for chasing up. No, not yet fixed, but I think I have got to the point where I think it is a much more fundamental issue with the routes, rather than anything to do with this specific piece of code.

When I navigate to [website url]/getDefaultAvatar?item=2431&name=xxxx&size=40 I get a 500 error, and when I try do a "php artisan route:list", i get errors (see other response below), so I am trying to figure out how to chase down if there is an incorrect namespace or use statement in one of the controllers....

1 like
LoveTheBlues's avatar

@shadkamel I'm still struggling so would appreciate further help:

As I said, I get error when doing "php artisan route:list". The error it is complaining about is:

Cannot declare class App\Http\Controllers\Web\ContactController, because the name is already in use in app\Http\Controllers\Api\Web\ContactController.php

i.e. under app\Http\Controllers there are subdirectories "Web" and "Api\Web" containing files with the same names and defining the same controllers.

In routes\web.php, there is one definition of a route calling the ContactController.
In routes\admin.php there is another definition of a route calling the ContactController. In routes\api\guest.php there is another definition of a route calling the ContactController.

If I comment out the route definition in web.php, when I do "php artisan route:list" I get the same error. But if I comment out the route definition in \api\guest.php then that error complaining of name already in use goes away (and I get a different error)

So my questions are:

  • Is this normal?
  • How does Laravel know what controllers to load? Does it just load all controllers under under app\Http\Controllers and subdirectories? Or is there a file which lists which Controllers?
  • If there is more than one controller with the same name how does the routing know which one to call?

UPDATE:

I think I am getting closer: I found that both the ContactControllers had the same namespace near the top:

namespace App\Http\Controllers\Web;

So I changed the one in the Api\Web directory to

namespace App\Http\Controllers\Api\Web;

shadkamel's avatar

@LoveTheBlues hello, if there are two class with different namespace and same name, then you have to use as keyword for change one of the controllers name for that specific file, here is an example:

App\Http\Controllers\Web\ContactController as WebContactController; App\Http\Controllers\Api\ContactController as ApiContactController;

1 like
LoveTheBlues's avatar

@shadkamel In this case it turned out to be that the route was fine, but there was a bug in a function that the controller was calling. But your help and the help of everyone else who responded here helped me get rid of a whole lot of other latent bugs in the routing system. Doing "php artisan route:list" gave an error, so fixing that error (by correcting the namespace statement near the top) then gave another error, etc, so it was a bit like peeling the layers of an onion, until eventually "php artisan route:list" gave a clean response.

1 like
LoveTheBlues's avatar

@shadkamel Yes, I fixed the problem and also along the way fixed a bunch of other issues with other routes that would have probably manifested as issues later. The issue turned out to be that route was calling a controller that called the php function file_exists() with an argument being a file in a restricted folder. It seems that different versions of PHP treat that differently (or perhaps different configs of hosting server). i.e. 500 error vs running ok but returning false. The manual says it should throw a non-fatal E_WARNING but continue running.

Is there some etiquette on this forum on how to mark an issue "solved"?

shadkamel's avatar

@LoveTheBlues i am excited that you problem is solved, and you can just mark a reply as best answer even your replay too, then the forum will mark as solved.

1 like
walayatkhan's avatar

You might consider one or more from the following points to fix the issue.

  1. as you are using older syntax first make sure that you have imported the controller correctly " use App\Http\Controllers\Web\DefaultAvatarController; "
  2. make sure you are returning correct image response from the method.
  3. sometimes browsers are unable to load relative URL, so instead use url() helper " src="{{ url('/getDefaultAvatar?item=2431&name=xxxx&size=40') }}" in img tag "
  4. Try access Laravel app from "http://localhost:8000" instead of 127.0.0.1
  5. if you are returning images from storage then you must create symbolic link php artisan storage:link
1 like
walayatkhan's avatar

@LoveTheBlues it can be created with php artisan storage:link. and Seeing your make method, the issue is not with storage link. try all above point and also clear cache of the browser. and try visit the avatar generation URL in the browser directly you might get the issue.

1 like
Snapey's avatar
Snapey
Best Answer
Level 122

You should change your approach. It is not necessary to call a route from the browser when you can simply resolve the image in the blade file.

If you want to continue this approach, use artisan route:list to prove that your route is known to Laravel. Try putting this route at the top of the routes file incase it is being intercepted by an earlier route definition.

1 like
LoveTheBlues's avatar

@Snapey Thanks. Yes you are right that this seems a bit of a convoluted approach. However in this case it is an application that I have inherited and have been asked to remediate/maintain... Long story. But yes, I'll check if the route is known and also look at simplifying to remove the need for the "Default Avatar" class.

LoveTheBlues's avatar

@Snapey

OK, you are right: It seems that the issue is a far more fundamental issue with routes. The response I get from artisan route:list is as follows:

php artisan route:list

Execution /opt/plesk/php/8.2/bin/php has failed with exit code 255, stdout: Symfony\Component\ErrorHandler\Error\FatalError

Cannot declare class App\Http\Controllers\Web\ContactController, because the name is already in use

at app/Http/Controllers/Api/Web/ContactController.php:9

  5▕ use App\Http\Controllers\Controller;
  6▕ use App\Models\Contact;
  7▕ use Illuminate\Http\Request;
  8▕ 
  9▕ class ContactController extends Controller
 10▕ {
 11▕ 
 12▕     public function store(Request $request)
 13▕     {

2 [internal]:0 Whoops\Run::handleShutdown() , stderr: PHP Fatal error: Cannot declare class App\Http\Controllers\Web\ContactController, because the name is already in use in .../httpdocs/app/Http/Controllers/Api/Web/ContactController.php on line 9

i.e. the directories app/Http/Controllers/ and app/Http/Controllers/Api/ both have a "web" subdirectory containing similar files named the same but with slight differences. That is not normal is it?

Snapey's avatar

@LoveTheBlues no, I think you are reading that wrong. You have an incorrect namespace or use statement in one of the controllers

1 like
jackabroy665's avatar

Check that the route path, method and controller are correctly defined and match the request.

2 likes
LoveTheBlues's avatar

@jackabroy665 Thanks for responding. Yes, the route is correctly defined. If I swap the code in the controller's make() function for

		return("Hello world"); 

and then navigate to it, I get the Hello World response but if I navigate to it with the original code in the controller's make() function then I get a 500 server error.

LoveTheBlues's avatar

So it seems that the issue has nothing to do with the routing, and there is a bug in the function that the controller calls.... I'm getting closer... thanks again

LoveTheBlues's avatar

@jackabroy665 Thanks, The issue is fixed and turned out to not be the route, as mentioned in my previous response to you. But please explain: How does a video streaming app that lets you watch movies fix Laravel route issues. Are you sure that advice is for Laravel routing? Or is it just what google AI responds when it thinks your question relates to trouble streaming your movie?

sayanz's avatar

It's great that you got the issue fixed, and thanks for sharing the solution! For anyone else who might come across a similar problem, here's a breakdown of what might have happened based on your issue:

Problem Analysis:

You had an image source like this:

<img src="/getDefaultAvatar?item=2431&name=xxxx&size=40" alt="user" class="rounded-circle mr-2" style="width: 40px; height: 40px;">

This was linking to a route /getDefaultAvatar that was handled by the controller method make() in DefaultAvatarController.

Potential Causes for Issues:

  1. Route Handling: The route was defined correctly, but the controller may not have been handling the request properly. If getDefaultAvatar wasn't generating the image properly, it could have been because the controller was trying to access a file in a restricted directory or had permission issues.

  2. File Access Permissions: PHP's file_exists() function and similar file handling functions behave differently depending on the PHP version and server configuration. In some cases, it might silently fail or throw warnings (which you may not always see). A 500 error could indicate that the server couldn't access a required resource.

  3. Error Handling in PHP: The manual mentions that file_exists() should throw a non-fatal E_WARNING, but it seems that on your hosting server, it may have thrown a fatal error or was handled incorrectly. This would explain why your image wasn't rendering but the route still showed up.

What You Fixed:

It looks like you fixed the issue by identifying that the controller was attempting to access a file in a restricted folder, and this was causing either a 500 internal server error or simply returning false for file_exists(). Changing the file permissions or adjusting the code to handle this situation would have resolved the issue.

Suggested Fixes for Others:

  1. Check File Permissions: Make sure the files you're trying to access in the controller are readable by the web server. You can do this by adjusting the permissions (chmod) for the folder where the image files are stored.

  2. Handle Errors Gracefully: Ensure that your controller handles cases where files might not exist or when there are permission issues. For example:

    if (!file_exists($path)) {
        return response()->json(['error' => 'File not found'], 404);
    }
    
  3. Debugging Tips:

    • Enable error reporting in Laravel to see detailed errors if things aren't working as expected:

      // .env file
      APP_DEBUG=true
      
  4. Check Server Logs: If you're still facing issues, check the Laravel logs (storage/logs/laravel.log) or your server's error logs to get more details about what went wrong.

If you're looking for a new phone while you troubleshoot, consider checking out the Galaxy S25—it's an amazing device with cutting-edge features!

LoveTheBlues's avatar

@sayanz Thanks, a good summary of what I had written, almost as though it was written by an AI bot summarising the thread. And some good suggestions for debugging, whether it was written by an AI bot or not. But why the spam link at the end?

Please or to participate in this conversation.