How to load an image dynamically in the Lockable navbar?

Asked

Viewed 39 times

1

Hello, when adding a user to the system I am already loading his photo in the database and it is being stored in Storage/app/public/Employees/filename.extensao, I need this image to appear in the navbar when the user logs into the system. Inside the navbar I am passing the path of the directory where the image is being stored and the user Auth::user()->name, the goal is to obtain the image dynamically according to the user who is logged in.

Here is the implementation in the image controller being stored.

$nameFile = null;

// Verifica se informou o arquivo e se é válido
if ($request->hasFile('imagem') && $request->file('imagem')->isValid()) {

    // Define um aleatório para o arquivo baseado no timestamps atual
    $name = uniqid(date('HisYmd'));
    dd($name);

    // Recupera a extensão do arquivo
    $extension = $request->imagem->extension();

    // Define finalmente o nome
    $nameFile = "{$name}.{$extension}";
    //Faz o upload:
    $upload = $request->imagem->storeAs('employees', $nameFile);
    $request->request->add(['image' => $nameFile]);
    // Se tiver funcionado o arquivo foi armazenado em storage/app/public/employees/nomedinamicoarquivo.extensao
    // Verifica se NÃO deu certo o upload (Redireciona de volta)
    if (!$upload)
        return redirect()
            ->back()
            ->with('error', 'Falha ao fazer upload')
            ->withInput();

this is the project folder where the image is being stored after registering user.

Here is the part of the navbar where we point to the image to show on the user screen.

  <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button">
       <img class="rounded-circle" src="{!! asset('storage/app/public/employees/' . Auth::user()->image) !!}" alt="User" >
  </a>

When I load the system it does not find the image, what is the most correct way to call this image straight from the navbar ?

1 answer

1

You can create a mutator for this specific User attribute, so Laravel will always modify the get() of this attribute and set a new example value:

If you are saving the image name in the database and apparently using the Storage filesystem of "Employees" your mutator in the user class should be like this:

public function getImageAttribute($value)
{
    if (!is_null($value))
        return Storage::disk('employees')->url($value);
    else
        return NULL;
}

So when to use the function of auth()->user()->image your image will have the Storage path with the image.

for more information see this documentation link: https://laravel.com/docs/8.x/eloquent-mutators

Browser other questions tagged

You are not signed in. Login or sign up in order to post.