Uploading images or files in Laravel

- Andrés Cruz

En español
Uploading images or files in Laravel

Este material forma parte de mi curso y libro completo; puedes adquirirlos desde el apartado de libros y/o cursos Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

We are going to learn how to load images in Laravel; for that, we are going to assume that you already have some form ready in Laravel.

In this case, we are going to work with uploading images to a post, which has the following structure, its model:

class Post extends Model
{
    protected $fillable = ['title', 'slug', 'content', 'category_id', 'description', 'posted', 'image'];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

The form view looks like the following:

The important thing to note here is the multipart form data field to enable file upload, and the file.

To process the form, we have the following:


<form action="{{ route('post.update',$post->id) }}" method="post" enctype="multipart/form-data">
        @method("PATCH")
 @csrf

<label for="">Título</label>
<input type="text" class="form-control" name="title" value="{{ old('title', $post->title) }}">

<label for="">Slug</label>
<input type="text" class="form-control" name="slug" value="{{ old('slug', $post->slug) }}">

<label for="">Categoría</label>
<select class="form-control" name="category_id">
    <option value=""></option>
    @foreach ($categories as $title => $id)
        <option {{ old('category_id', "$post->category_id") == $id ? 'selected' : '' }} value="{{ $id }}">
            {{ $title }}</option>
    @endforeach
</select>

<label for="">Posteado</label>
<select class="form-control" name="posted">
    <option {{ old('posted', $post->posted) == 'not' ? 'selected' : '' }} value="not">No</option>
    <option {{ old('posted', $post->posted) == 'yes' ? 'selected' : '' }} value="yes">Si</option>
</select>

<label for="">Contenido</label>
<textarea class="form-control" name="content"> {{ old('content', $post->content) }}</textarea>

<label for="">Descripción</label>
<textarea class="form-control" name="description">{{ old('description', $post->description) }}</textarea>


<label for="">Imagen</label>
<input type="file" name="image">

<button type="submit" class="btn btn-success mt-3">Enviar</button>
       
</form>

And the function to process the form:

public function update(PutRequest $request, Post $post)
    {
       // Resto de la funcion de carga 
        $data = $request->validated();
        if( isset($data["image"])){
            $data["image"] = $filename = time().".".$data["image"]->extension();
            $request->image->move(public_path("image/otro"), $filename);
        }
        $post->update($data);
}

It is very simple; remember that uploading files in Laravel is disk-based, a disk is anything that can store files, as in this case it would be a local folder to the project, but it could be another service like Amazon Web Server; you can verify this in the config/filesystem.php file.

For the rest, since we have the image as an optional payload, we ask if it is defined; we generate the name of the image with the time() function and save it to a "disk", which is our local folder.

And that's it, with this, we can load our files in Laravel.

Remember that this post is part of my course and book on Laravel.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.