mardi 23 juillet 2019

Laravel Upload Multiple Images all records with same name and not moved files

I am new in Laravel and I develop a web application where someone can upload a car ad and other users can write comments bellow that. Instead of developing a simple CRUD application I thought about developing also a table that will be related to these ads and will store the photos. Up to this point, I have made the relations, I can show images and I have two problems: The first problem is that not all images are moved to storage/photos folder and the second problem is that all the records in the database have the same name. For example, if I want to upload images 1,2,3 then in the database all the files will have the name 1.

Bellow, you may find the store code. This code stores all the ads and also the images if they exist.

public function store(Request $request)
{
    //
    $this->validate($request, [
        'name' => 'required',
        'cc' => 'required',
        'desc' => 'required',
        'date' => 'required'
    ]);
    $ad = new Ad;

    $ad->name = $request->input('name');
    $ad->cc = $request->input('cc');
    $ad->desc = $request->input('desc');
    $ad->date = $request->input('date');
    $ad->user_id = auth()->user()->id;
    $ad->save();

    if ($request->hasFile('photos')) {
        $allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
        $files = $request->file('photos');
        foreach ($files as $file) {
            $filename = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            //$file->move('storage/photos', $filename); 
            $check = in_array($extension, $allowedfileExtension);

            if ($check) { 
                foreach ($request->photos as $photo) {
                    $photo->move('storage/photos', $filename); 
                    $img = new AdsPhoto;
                    $img->ad_id = $ad->id;
                    $img->filename = $filename;
                    $img->save();
                }
                return redirect('/home')->with('success', 'ad + image created');
            } else {
                echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
            }
        }
    }
    return redirect('/home')->with('success','ad created');
}

Thank you in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire