Fahad
Fahad

Reputation: 65

I can not store info in DB in Laravel 7

I have an issue with store info into the MySQL database, and I try to change the method that stores info into DB, but it still the same problem. Moreover, I need your help to figure out the problem and solve it.

PostController

<?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();
}

Post Model

<?php
class Post extends Model
{
    //

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

Form

       <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>

I appreciate your effort to help me, and thanks in advance.

Upvotes: 1

Views: 124

Answers (1)

Donkarnash
Donkarnash

Reputation: 12835

To get the file of the request object you can access it via file() method. And why are you not using method injection for the request

//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();
}

Upvotes: 1

Related Questions