article

Monday, August 1, 2022

Laravel 9 REST API Upload Image

Laravel 9 REST API Upload Image

Laravel 9 Upload Image and Display

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Post -m

A new file named Post.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Post.php
//app/Models/Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
    	'name', 
    	'image', 
    	'description'
    ];
}
laravelproject\database\migrations\create_posts_table.php
//laravelproject\database\migrations\create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->text('description');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table
Create Controller and Request
C:\xampp\htdocs\laravel\laravelproject>php artisan make:controller PostController -r

laravelproject\app\Http\Controllers\PostController.php
//laravelproject\app\Http\Controllers\PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;
use App\Http\Requests\PostStoreRequest;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class PostController extends Controller
{
    public function store(PostStoreRequest $request)
    {
        try {
            $imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
    
            // Create Post
            Post::create([
                'name' => $request->name,
                'image' => $imageName,
                'description' => $request->description
            ]);
    
            // Save Image in Storage folder
            Storage::disk('public')->put($imageName, file_get_contents($request->image));
    
            // Return Json Response
            return response()->json([
                'message' => "Post successfully created."
            ],200);
        } catch (\Exception $e) {
            // Return Json Response
            return response()->json([
                'message' => "Something went really wrong!"
            ],500);
        }
    }
}
Next, create a Request

C:\xampp\htdocs\laravel\laravelproject>php artisan make:request PostStoreRequest
laravelproject\app\Http\Requests\PostStoreRequest.php
//laravelproject\app\Http\Requests\PostStoreRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        //return false;
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        if(request()->isMethod('post')) {
            return [
                'name' => 'required|string|max:258',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        } else {
            return [
                'name' => 'required|string|max:258',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        }
    }

    /**
     * Custom message for validation
     *
     * @return array
     */
    public function messages()
    {
        if(request()->isMethod('post')) {
            return [
                'name.required' => 'Name is required!',
                'image.required' => 'Image is required!',
                'description.required' => 'Descritpion is required!'
            ];
        } else {
            return [
                'name.required' => 'Name is required!',
                'description.required' => 'Descritpion is required!'
            ];   
        }
    }
}
Routes
All API requests will need the header Accept: application/json.
open routes/api.php and update the following code
laravelproject\routes\api.php
//laravelproject\routes\api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('posts', [PostController::class, 'store']); 
generate symbolic links C:\xampp\htdocs\laravel\laravelproject>php artisan storage:link

Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

open postman new request POST http://127.0.0.1:8000/api/posts

https://www.postman.com/downloads/

Related Post