简体   繁体   中英

How to upload image to Mysql via Laravel

I'm trying to upload image from a form to my Database. I am new to Laravel.

My WebuserController

 <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Webuser;

class WebuserController extends Controller
{
    public function index(){
        $webuser = Webuser::all();

        return $req->file('file')->store('docs');
        
    }

    public function store(Request $request) {
        Webuser::create([
            'name' => $request->name,
            'surname' => $request->surname,
            'email' => $request->email,
            'image' => $request->image
            
        ]);
            return back();
        
    }

}

Webuser Model

<?php

namespace App\Models;

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

class Webuser extends Model
{
    use HasFactory;

    protected $table = "webuser";

    protected $fillable = ['name', 'surname', 'email', 'image'];
}

Migration file

<?php

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

class CreateWebuser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('webuser', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('surname');
            $table->string('email');
            $table->string('image')->nullable();
            $table->timestamps();
        });

        
    }

    

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

Main view file

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            @import url(https://fonts.googleapis.com/css?family=PT+Sans:400,400italic);

@import url(https://fonts.googleapis.com/css?family=Droid+Serif);

html, body{
  background-image: url('https://wallpaperaccess.com/full/1146666.jpg');
}

body{
  counter-reset:section;
  text-align:center;
}

.container{
  position:relative;
  top:100px;
}

.container h1, .container span{
  font-family:"Pt Sans", helvetica, sans-serif;
}

.container h1{
  text-align:center;
  color:#fff;
  font-weight:100;
  font-size:2em; 
  margin-bottom:10px;
}

.container h2{
  font-family:"droid serif";
  font-style:italic;
  color:#d3b6ca; 
  text-align:center;
  font-size:1.2em;
}

.container form span:before {
  counter-increment:section;
  content:counter(section);
  border:2px solid #4c2639;
  width:40px;
  height:40px;
  color:#fff;
  display:inline-block;
  border-radius:50%;
  line-height:1.6em;
  font-size:1.5em;
  position:relative;
  left:-22px;
  top:-11px;
  background:#2F1E27;
}

form{
  margin-top:25px;
  display:inline-block;
}

.fields{
  border-left:2px solid #4c2639
}

.container span{
    margin-bottom:22px; 
    display:inline-block;
}

.container span:last-child{
   margin-bottom:-11px;
}

input{
  border:none;
  outline:none;
  display:inline-block;
  height:34px;
  vertical-align:middle;
  position:relative;
  bottom:14px;
  right:9px;
  border-radius:22px;
  width:220px;
  box-sizing:border-box;
  padding:0 18px; 
}

input[type="submit"]{ 
  background:rgba(197,62,126,.33) ! important;
  color:#fff;
  position:relative;
  left:9px;
  top:25px; 
  width:100px;
  cursor:pointer;
}

    </style>
</head>
<body>

<div class="container">
  <h2></h2>
  <h1>Road to the moon is here!</h1>
  
  <form method="POST" action="{{ route('add-user') }}" id="join-us" enctype="multipart/form-data"> 
  @csrf
    <div class="fields">
    
    <span>
       <input placeholder="Name" type="text" name="name" required>
    </span>
    
    <br/>
    
     <span>
       <input placeholder="Surname" type="text" name="surname" required>
    </span>
    
    <br/>

    <span>
       <input placeholder="E-mail" type="text" name="email" required>
    </span>

    <br/>

    <div class="submit">
    <input type="file" id="myFile" name="image" value="upload" required>
    </div>

    </div>

    <br>  

    <div class="submit">
      <input class="submit" value="Submit" type="submit" />
    </div>
  </form>
</div>

</body>
</html>

Web.php route file

<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\WebuserController;
use App\Models\Webuser;


Route::get('/', function () {
    return view('main');
})->name('main');



/*Route::get('user/add', function(){
    DB::table('webuser')->insert([
        'name' => 'Emin',
        'surname' => 'Yilmaz',
        'email' => 'emin@gmail.com',
        'image' => 'favicon.ico'
    ]);
});*/

/*Route::get('webuser', function(){
    $webuser = Webuser::find(1);
    return $webuser->name;
    
});*/

Route::get('users', [WebuserController::class, 'index']);

/*Route::post('/ad', [WebuserController::class, 'store'])->name('add-user');*/

View file

Mysql side

As you can see, I already finished the form. But the way I try to upload the images is not right. I watched videos on yt but didn't help me. How can I overcome this issue?

If you store your image files in your db, you will have issues with query time. It will be much more efficient to store images under your project's /public directory and store relative paths of images in db like "/products/images/image1.jpeg".

For example, lets say that you have a $webuser and you are taking image from form
to save as $webuser->profile_picture. You should store it using something like this in your WebUserController.php:

$webuser = Webuser::first();

$webuser->profile_picture =
$request->file('image')->storeAs('webuser/images',"webuser.".$webuser->id.".jpeg");

$webuser->save();

If you save image like this, you should have that image from request at
"public/webuser/images/webuser1." (If user id is 1).

Then if you ever want to use that image in somewhere, all you have to do is call a query to take the relative url of image file.

If you are dealing with different image types, you can get MimeType and use it like this:

$MimeType = explode ( "/" , $request->file('image')->getMimeType() );

$webuser->profile_picture =
$request->file('image')->storeAs('webuser/images',"logo.".$MimeType[1]);

WebuserController:

class WebuserController extends Controller
{
    public function index() {
        $webusers = Webuser::all();
        return $webusers; 
    }

    public function store(Request $request) {
        $file               =       $request->file('image');
        $file_origname      =       $file->getClientOriginalName();
        $file_origext       =       $file->getClientOriginalExtension();
        $file_realpath      =       $file->getRealPath();
        $file_docsize       =       round(($file->getSize())/1024, 2);
        $file_mimetype      =       $file->getMimeType();
        $file_giveenname    =       date('YmdHis').Rand().'.'.$file_origext;

        Webuser::create([
            'name' => $request->name,
            'surname' => $request->surname,
            'email' => $request->email,
            //---Image Details
            'original_name'     =>      $file_origname,
            'extension'         =>      $file_origext,
            'pathname'          =>      $file_realpath,
            'size'              =>      $file_docsize,
            'mimetype'          =>      $file_mimetype,
            'image'             =>      $file_giveenname,
        ]);
        Storage::putFileAs('public/', $file, $file_giveenname);
        return back();
    }
}

Migration File:

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

class CreateWebuser extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('webuser', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('surname');
            $table->string('email');
            $table->string('original_name');
            $table->string('extension');
            $table->string('pathname');
            $table->string('size');
            $table->string('mimetype');
            $table->string('image')->nullable();
            $table->timestamps();
        });
    }

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

When you want to view your image, just run the following artisan code:

php artisan storage:link

It will create an image of your storage folder inside your public folder.

If you want to view your all your images, use the following code:

@if($webusers)
    @foreach($webusers AS $webuser)
        <img src="{{ url('/storage/'.$webuser['image']) }}" style="width: 870px; height: 370px;" alt="">
    @endforeach
@endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM