19 Years of Excellence 99% Hiring Rate

How to Upload an Image with Title and Description in Laravel

ADMEC Multimedia Institute > Web Development > How to Upload an Image with Title and Description in Laravel

Hello readers, welcome to our another blog on Laravel! This blog shares the tips on How to Upload an Image with Titles and Description in Laravel. This tutorial will take you through setting up a Laravel project, creating a database, and configuring models. You will learn controllers and views to handle file upload in Laravel too. We will be talking about the validation and storage of images while upload images. You will also know on security and common issues to avoid while uploading.

By the end, you’ll have a complete knowledge of creating posts with images and files upload feature. Whether you’re new to Laravel or looking to enhance your skills, this blog will surely help you. Let’s get started!

Before we begin, let’s thoroughly explore the necessary steps to install Laravel, ideal for those new to this framework!

Step 1: Open a terminal and set your desired path for creating the project.

Step 2: Now write the command “composer create-project laravel/laravel post_a_blog“. This command will provide us with all the necessary files and a sample template for our project.

Step 3: The next command is “cd [project-name]“ to open the project in the terminal.

Step 4: To view the sample template, we can use the command “php artisan serve“.

Step 5: Now let’s create a database with the name “lara_blogposting” in MySQL, where we will store our blog data. Also, set the same DB name in the .env file to make a database connection with our project.

Step 6: After setting up all the above requirements, we will now start to code for our blog posting project. 

(I) We will first create a model using the command “php artisan make: model Blog” and write the following code in it:

In post_a_blog/app/Models/Blog.php

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
use HasFactory;
public $fillable = ['pics', 'date', 'title', 'description'];
}

(ii) Next, we will make a controller using the command “php artisan make: controller BlogController“ and write the following code in it:

    In post_a_blog/app/Http/Controllers/BlogController.php

    <?php
    namespace App\Http\Controllers;

    use App\Models\Blog;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;

    class BlogController extends Controller
    {
    public function index()
    {
    $blogs = Blog::paginate(9);
    return view('blogs.index', ['blogs' => $blogs]);
    }

    public function create()
    {
    return view('blogs.create');
    }

    public function store(Request $request)
    {
    $request->validate([
    'title' => 'required',
    'date' => 'required',
    'description' => 'required',
    'pics' => 'required|image|mimes: jpeg, png, jpg, gif,svg|max:2048',
    ]);

    $input = $request->all();
    if ($image = $request->file('pics')) {
    $destinationPath = 'uploads/';
    $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
    $image->move($destinationPath, $profileImage);
    $input['pics'] = "$profileImage";
    }
    Blog::create($input);
    return back()->with('msg', 'Blog added successfully.');
    }
    }

    (iii) After creating the model and controller, we will code for the view of our project:

    (a) Create a folder inside views with the name ‘layouts’ to keep the header and footer files

        In post_a_blog/resources/views/layouts/header.blade.php

        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        </head>
        <body>
        <nav class="navbar navbar-expand-lg bg-body-tertiary">
        <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
        <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
        Dropdown
        </a>
        <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
        <li><hr class="dropdown-divider"></li>
        <li><a class="dropdown-item" href="#">Something else here</a></li>
        </ul>
        </li>
        <li class="nav-item">
        <a class="nav-link disabled" aria-disabled="true">Disabled</a>
        </li>
        </ul>
        <form class="d-flex" role="search">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
        </form>
        </div>
        </div>
        </nav>

        In post_a_blog/resources/views/layouts/footer.blade.php

        <div class="card">
        <div class="card-header">
        Footer
        </div>
        <div class="card-body">
        <h5 class="card-title">Special title treatment</h5>
        <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
        </div>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
        </body>
        </html>

        In post_a_blog/resources/views/layouts/main.blade.php

        @include('layouts.header')
        @yield('main-container')
        @include('layouts.footer')

        (b) Create a folder inside views with the name ‘blogs’ to keep the blog index and blog create files

        In post_a_blog/resources/views/blogs/index.blade.php

        @extends('layouts.main')
        @section('main-container')
        <div class="blog_section layout_padding">
        <div class="container">
        <div class="row">
        <div class="col-md-12">
        <h1 class="blog_taital">Latest Blogs</h1>
        <a href="/blog/create" class="btn btn-success">Add Blog</a>
        </div>
        </div>
        <br>
        <div class="blog_section_2">
        <div class="row">
        @foreach ($blogs as $blog)
        <div class="col-md-4">
        <div class="blog_img"><img src="/uploads/{{ $blog->pics }}"></div>
        <div class="btn_main">
        <div class="date_text">{{ $blog['date'] }}</div>
        </div>
        <div class="blog_box">
        <h3 class="blog_text">{{ $blog['title'] }}</h3>
        <p class="lorem_text"> {{ $blog['description'] }}</p>
        </div>
        </div>
        @endforeach
        </div>
        </div>
        </div>
        </div>
        @endsection

        In post_a_blog/resources/views/blogs/create.blade.php

        @extends('layouts.main')
        @section('main container)
        @if (Session::has('msg'))
        <div class="alert alert-danger">{{ Session::get('msg') }}</div>
        @endif
        <div class="container">
        <div class=" panel panel-primary">
        <div class="panel-body">
        @if (count($errors) > 0)
        <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
        </ul>
        </div>
        @endif

        <div class="cta-form">
        <h2>Add Blog</h2>
        <p></p>
        </div>
        <form action="/blog/create" method="post" enctype="multipart/form-data">
        {{ csrf_field() }}
        <label for="title" class="form__label">Title</label>
        <input type="text" name="title" placeholder="Title" class="form__input" id="title" />
        <br><br>
        <label for="date" class="form__label">Date</label>
        <input type="text" name="date" placeholder="date" class="form__input" id="date" />
        <br><br>
        <label for="description" class="form__label">Description</label>
        <input type="text" name="description" placeholder="description" class="form__input" id="description" />
        <br><br>
        <label for="Upload-image">Upload-image</label>
        <input type="file" name="pics" class="form-control">
        <br><br>
        <button type="submit" class="btn btn-success">Upload</button>
        </form>
        </div>
        </div>
        </div>
        @endsection

        (iv) To store blog data, we will create a table in the database using migration. The command for migration will be “php artisan make: migration create_blogs_table”. Add the following code in the migration file: 

          In post_a_blog/database/migrations/2024_06_16_105341_create_blogs_table.php

          <?php
          use Illuminate\Database\Migrations\Migration;
          use Illuminate\Database\Schema\Blueprint;
          use Illuminate\Support\Facades\Schema;

          return new class extends Migration
          {
          /**
          * Run the migrations.
          */
          public function up(): void
          {
          Schema::create('blogs', function (Blueprint $table) {
          $table->id();
          $table->string('pics');
          $table->string('date');
          $table->string('title');
          $table->text('description');
          $table->timestamps();
          });
          }


          /**
          * Reverse the migrations.
          */
          public function down(): void
          {
          Schema::dropIfExists('blogs');
          }
          };

          (v) Now, to create the specified table in the database, we will use the command “php artisan migrate”.

          (vi) At last, we will set routes.

              In post_a_blog/routes/web.php

              <?php
              use Illuminate\Support\Facades\Route;
              use App\Http\Controllers\BlogController;

              Route::get('/', [BlogController::class, 'index']);
              Route::get('/blog/create', [BlogController::class, 'create']);
              Route::post('/blog/create', [BlogController::class, 'store']);

              Step 7: As we have made changes in the routes, we have to use the command “php artisan optimize” to optimize the routes.

              Step 8: Finally, now it’s time to run our project using the command “php artisan serve”.

              Our home page will have the following output

              runing laravel project

              Creating a blog page will have the following output

              Creating blog page in laravel

              After adding a new blog, our home page will look something like this:

              homepage showing blogs in laravel

              By following this tutorial, you can upload an image with Title and Description in Laravel without any problem. I hope you will find these steps easy to understand and you will use them in improving your Laravel projects.

              Explore beyond one framework! Enrich your skills as a versatile web developer with our comprehensive course at the Web Development Institute in Delhi.

              Those who are new to programming can go for professional courses at the Web Development Institute in Delhi

              PHP knowledge of Laravel is incomplete, make it complete with our master course on PHP and Laravel.

              Thank you for following along, and happy coding! If you have any questions or need further assistance, feel free to reach out at ADMEC Multimedia Institute in Delhi.

              Ready to level up your Laravel skills?

              Dive into advanced techniques with our certificate course at ADMEC Multimedia. Master MVC architecture and create robust web applications using PHP Laravel with us.

              Get Syllabus

              About Author of Upload an Image with Title and Description in Laravel

              Hi, I’m Vishnu, a computer science student with a keen interest in web design. Currently pursuing a No.1 Diploma in Web Design and Development. I’m passionate about creating user-friendly and visually engaging websites. My journey is fueled by a love for blending creativity with cutting-edge technology to enhance digital experiences.

              Related Posts

              Leave a Reply

              Talk to Us