繁体   English   中英

我无法在 Laravel 7 的数据库中存储信息

[英]I can not store info in DB in Laravel 7

我在将信息存储到 MySQL 数据库时遇到问题,我尝试更改将信息存储到 DB 的方法,但仍然是同样的问题。 此外,我需要你的帮助来找出问题并解决它。

后控制器

<?php 
public function store(){
    $inputs= request()->validate([
        'title'=>'required|min:8|max:100',
        'post_image'=>'file',
        'body'=>'required'
    ]);
    if (request('post_image')){
        $inputs['post_image']=request('post_image')->store('images');
    }
    auth()->user()->posts()->create($inputs);
    return back();
}

发布 Model

<?php
class Post extends Model
{
    //

    protected $guarded =[];
    public function user(){
        return $this->belongsTo(User::class);
    }
    public function getPostImageAttribute($value){
        return asset($value);
    }
}

形式

       <form action="{{route('post.store')}}" method="post" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
                <lable for="title">Title</lable>
                <input type="text" name="title" class="form-control" placeholder="Enter title">
            </div>

            <div class="form-group">
                <lable for="file">File</lable>
                <input type="file" name="post_image" class="form-control-file" id="post_image" placeholder="Upload your image">
            </div>
            <div class="form-group">
                <lable for="exampleInputEmail"></lable>
                <textarea  name="body" cols="30" rows="10" class="form-control"></textarea>
            </div>
            <button type="submit" class="btn btn-primary"> Submit</button>
        </form>

感谢您为帮助我所做的努力,并在此先感谢您。

要获取请求 object 的文件,您可以通过 file() 方法访问它。 以及您为什么不对请求使用方法注入

//use Illuminate\Http\Request; - import the use statement at top

public function store(Request $request){
    $inputs= $request->validate([
        'title'=>'required|min:8|max:100',
        //'post_image'=>'file',
        'body'=>'required'
    ]);
    if ($request->hasFile('post_image') && $request->file('post_image')->isValid()){
        $inputs['post_image'] = $request->file('post_image')->store('images');
    }
    auth()->user()->posts()->create($inputs);
    return back();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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