srikanthgopi's avatar

Laravel Upload Image, filename saved to database

I'm using Laravel 5.6 and Collective HTML.

I have a table articles and im creating a form to upload a asingle article

ArticleController

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categories = ArticleCategory::pluck('name', 'id');
        return view('backend.articles.create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $article = new Article();
        $article->title = $request->get('title');
        $article->category_id = $request->get('category_id');
        $article->subtitle = $request->get('subtitle');
        $article->image = $request->get('image');
        $article->description = $request->get('description');
        $article->save();
        return back()->with('success', 'Your article has been added successfully. Please wait for the admin to approve.');
    }

View

{!! Form::open(['route'=>'articles.store']) !!}

                  <div class="form-group {{ $errors->has('category_id') ? 'has-error' : '' }}">
                  {!! Form::select('category_id', $categories, null, ['class'=>'form-control', 'placeholder'=>'Choose Category']) !!}
                  <span class="text-danger">{{ $errors->first('category_id') }}</span>
                  </div>

                  <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
                  {!! Form::text('title', old('title'), ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!}
                  <span class="text-danger">{{ $errors->first('title') }}</span>
                  </div>

                  <div class="form-group {{ $errors->has('subtitle') ? 'has-error' : '' }}">
                  {!! Form::text('subtitle', old('subtitle'), ['class'=>'form-control', 'placeholder'=>'Upload subtitle']) !!}
                  <span class="text-danger">{{ $errors->first('subtitle') }}</span>
                  </div>

                  <div class="form-group {{ $errors->has('image') ? 'has-error' : '' }}">
                  {!! Form::file('image', old('image'), ['class'=>'btn-white form-control', 'placeholder'=>'Enter image Url']) !!}
                  <span class="text-danger">{{ $errors->first('image') }}</span>
                  </div>

                  <div class="form-group {{ $errors->has('description') ? 'has-error' : '' }}">
                  {!! Form::textarea('description', old('description'), ['class'=>'form-control', 'placeholder'=>'Enter Description']) !!}
                  <span class="text-danger">{{ $errors->first('description') }}</span>
                  </div>

                  <div class="form-group">
                  <button class="btn btn-primary">Submit</button>
                  </div>

                {!! Form::close() !!}

I'm using this package for slugs : https://github.com/cviebrock/eloquent-sluggable

When i create an article a slug is automatically formed based on the title. What i want to achieve is to upload a image file(jpg, png, jpeg) and save the image name to the database and the image to public/uploads/articles folder.

When i say image name, i want the imagename to be the slug of the article iike for example

If i create Article 1, a slug is automatically created article-1, i want the image name to be article-1.jpg(the image extension) to be saved in the database and save the image article-1.jpg to the public folder.

How to rename the file and achieve this functionality.

0 likes
3 replies
lostdreamer_nl's avatar

first, add the correct enctype to the form, or the image wont upload at all (and in the POST data you'll only find the name of the file instead of the file).

{!! Form::open(['route'=>'articles.store', 'files' => true]) !!}

Then in the controller you could do something like:


    public function store(Request $request)
    {
        $article = new Article();
        $article->title = $request->get('title');
        $article->category_id = $request->get('category_id');
        $article->subtitle = $request->get('subtitle');
        $article->description = $request->get('description');
        $article->save();

        $article->image = $request->file('image')->storeAs(
                'my-folder-name', $article->slug
        );
        $article->save();

        return back()->with('success', 'Your article has been added successfully. Please wait for the admin to approve.');
    }

Now it will upload the file in /storage/my-folder-name/{slug}.{ext} and it's path will be saved to $article->image.

Note: Use the request object to validate that 'image' is an actual image ;)

srikanthgopi's avatar

@lostdreamer_nl

I'm saving all the images in public/uploads/articles/ folder directly and not in storage folder so do i need to mention

$request->file('image')->storeAs(
                'public/uploads/articles./', $article->slug
        );

And it doesn't save the image name in the database. I mean I just want the image name as article slug to be saved in the database along with the image extension. and the file to be renamed with article slug and moved to the public/uploads/articles folder

The reason i choose to not save images in the storage folder is because im using a shared hosting which doesn't have command line interface to create storage:link

srikanthgopi's avatar
srikanthgopi
OP
Best Answer
Level 2

Tried

 /**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate($request, [
      'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $article = new Article();

    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $name = str_slug($request->title).'.'.$image->getClientOriginalExtension();
        $destinationPath = public_path('/uploads/articles');
        $imagePath = $destinationPath. "/".  $name;
        $image->move($destinationPath, $name);
        $article->image = $name;
      }

      $article->title = $request->get('title');
      $article->category_id = $request->get('category_id');
      // $article->image = str_slug($request->get('image'));
      $article->subtitle = $request->get('subtitle');
      $article->description = $request->get('description');

      $article->save();
      return back()->with('success', 'Your article has been added successfully. Please wait for the admin to approve.');
}

it worked

Please or to participate in this conversation.