ds342222222 2019-07-14 14:50
浏览 82

Laravel 5.8显示描述和更改图片配置文件

I try to create/modify a profile, but when I want to add an image in profile, it doesn't work and doesn't load into the database.

ProfileController

class ProfileController extends Controller
{
    public function show(User $user)
    {
        return view('profile.show', compact('user'));
    }

    public function edit(User $user)
    {
        $this->authorize('update', $user->profile);
        return view('profile.edit', compact('user'));
    }

    public function update(User $user)
    {
        $this->authorize('update', $user->profile);
        $data = request()->validate([
            'description' => 'required',
            'image' => 'sometimes|image|max:3000'
        ]);

        if (request('image')) {
            $imagePath = request('image')->store('avatars', 'public');

            $image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
            $image->save();

            auth()->user()->profile->update(array_merge($data,
                ['image' => $imagePath]
            ));
        } else {
            auth()->user()->profile->update($data);
        }

        auth()->user()->profile->update($data);

        return redirect()->route('profile.show', ['user' => $user]);
    }
}

User

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $fillable = [
        'username', 'nom', 'prenom', 'adresse', 'ville',
        'codepostale', 'datedenaissance', 'email', 'password',
    ];


    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::created(function ($user) {
            $user->profile()->create([
                'description' => $user->username
            ]);
        });
    }

    public function getRouteKeyName()
    {
        return 'username';
    }

    public function profile()
    {
        return $this->hasOne('App\Profile');
    }

    public function posts()
    {
        return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
    }
}

show.blade.php

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-4">
                <img src="{{ $user->profile->getImage() }}" class="rounded-circle w-100" alt="" style="max-width: 240px;">
            </div>
            <div class="col-8">
                <div class="d-flex align-items-baseline">
                    <div class="h4 mr-3 pt-2">{{ $user->username }}</div>
                    <button class="btn btn-primary">S'abonner</button>
                </div>
                <div class="d-flex">
                    <div class="mr-3">{{ $user->posts->count() }} article(s) en vente
                    </div>
                    @can('update', $user->profile)
                        <a href=" {{ route('profile.edit', ['username' => $user->username]) }}">Modifier Profile</a>
                    @endcan
                    <div class="mt-3">
                        <div class="font-weight-bold">
                            {{ $user->profile->title }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="row mt-5">
                @foreach ($user->posts as $post)
                    <div class="col-4">
                        <a href="{{ route('posts.show', ['post' => $post->id]) }}">
                            <img src="{{ asset('storage') . '/' . $post->image }}" alt="" class="w-100">
                        </a>
                    </div>
                @endforeach
            </div>
        </div>
    </div>
@endsection

edit.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Modifier profile</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('profile.update', ['user' => $user]) }}" enctype="multipart/form-data">
                        @csrf
                        @method('PATCH')

                        <div class="form-group">
                            <label for="description">Description</label>

                            <div class="col-md-6">
                                <textarea id="description" type="text" class="form-control @error('description') is-invalid @enderror" name="description" autocomplete="description" autofocus>{{ old('description') ?? $user->profile->description }}</textarea>

                                @error('description')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>


                        <div class="form-group">    
                            <div class="custom-file">

                                <input type="file" name="image" class="custom-file-input @error('image') is-invalid @enderror" id="validatedCustomFile" >
                                <label class="custom-file-label" for="validatedCustomFile">Choisir une image</label>
                                @error('image')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    Modifier profile
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Profile.php

class Profile extends Model
{
    protected $fillable = ['description']; 

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function getImage()
    {
        $imagePath = $this->image ?? 'avatars/default.png';

        return "/storage/" . $imagePath;
    }
}

create_profiles_tables.php

class CreateProfilesTable extends Migration
{
    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('description')->nullable();
            $table->string('image')->nullable();
            $table->unsignedBigInteger('user_id')->index();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('profiles');
    }
}

I don't know what problem for uploads pictures in the database and change profile picture, can someone help?

  • 写回答

1条回答 默认 最新

  • dqxboe2628 2019-07-14 19:23
    关注

    In this instance, you are attempting to update the image field of the user's related Profile model.

    auth()->user()->profile->update(array_merge($data,
        ['image' => $imagePath]
    ));
    

    However, in your Profile model, image is not an allowed field for mass assignment.

    protected $fillable = ['description']; 
    

    You should change this to:

    protected $fillable = ['description','image']; 
    

    Hope this helps and good luck!

    EDIT

    Follow up to blank image problem.

    Based on that other solution I linked, I'm able to determine from the documentation that there are multiple ways to use the Intervention Image package.

    Try changing this:

    $image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
    $image->save();
    

    To this:

    $image = Image::make(Input::file('image'))->fit(800, 800);
    $image->save(public_path("/storage/{$imagePath}"));
    

    Perhaps you will have better luck with this method, just as the user did in the other thread.

    Intervention Image (documentation)

    make() http://image.intervention.io/api/make

    save() http://image.intervention.io/api/save

    EDIT

    Further follow-up

    Have you properly linked your public storage? If not, this could be a contributing factor.

    php artisan storage:link
    

    It's going to be very difficult for me to debug your app remotely. But I would start by creating some simple controller methods for testing.

    First, create a controller method to return a known good image. This would be one that you have placed directly on the server in a specific location. Then reference that path accordingly, and call the method from a route.

    public function untouchedImage()
    {
        $path = public_path('images/known-good-image.png');
        return response()->file(public_path($path);
    }
    

    Then, if the image above displays properly, create another controller method. Reference the exact same file location but attempt to output a resized image.

    public function resizedImage()
    {
        $path = public_path('images/known-good-image.png');
        $image = Image::make(path)->resize(40,40);
    
        return $image->response('png');
    }
    

    If this works, then the problem is likely with your image paths. You will need to dump the paths line by line in your app while you are saving the image to see what is going wrong.

    If it doesn't work, then you likely have a misconfiguration somewhere with Laravel or PHP. Do you have the proper PHP image libraries loaded on your server? It uses GD by default or Imagick through the config.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算