简体   繁体   中英

How to change the name of the downloaded file when editing in Laravel?

if (isset($article) && isset($article->id))


    <option value="0" {{ ($article->published == 0) ? 'selected' : '' }}>Publish</option>
    <option value="1" {{ ($article->published == 1) ? 'selected' : '' }}>No publish</option>
@else
    <option value="0" selected disabled>No publish</option>
    <option value="1" disabled>Publish</option>
@endif
<img src="{{URL::to('/images').'/'.$article->image_path}}" alt="">
<input type="file" name="image_path" />


function upload(Request $request){

  $image = $request->file('image_path');

  $new_name = rand() . '.' . $image->getClientOriginalExtension();

  $image->move(public_path('images'), $new_name);
  return $new_name; 
}


   public function update(Request $request, Article $article)
{
    $article->update($request->except('slug'));


    $article->categories()->detach();

    if($request->input('categories'))  :
        $article->categories()->attach($request->input('categories'));
    endif;
    return redirect()->route('admin.article.index');    
}

I need when I go to the editing page, and there is a picture, to be remembered otherwise when entering, even if it is there and I don not edit anything, then the database remains empty.

When I create a new post and save a new picture everything is fine, but when I edit, I need to remember what is already there, and if I do not change, then save the same to the database unless I upload another.

Try this:

public function update(Request $request, Article $article)
{
    $article->update($request->except('slug', 'image_path'));

    if ($request->hasFile('image_path')) {

        // Add your file upload logic here
        $image = $request->file('image_path');
        $new_name = rand() . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('images'), $new_name);

        $article->image_path = $new_name;
        $article->save();
    }

    $article->categories()->detach();

    if ($request->has('categories')) {
        $article->categories()->attach($request->input('categories'));
    }

    return redirect()->route('admin.article.index');
}

SourceLaravel docs

You can also read more about file uploads to enhance your code: https://laravel.com/docs/6.x/requests#files

First you need to check or match in the database that file exists or not like:

I assume you have update perticular record. Means single record. And 'image_path' means name of the image right?

  If( $article->image_field_name == $request->input('image_path'){
          //Your update logic here.

  }

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