mardi 27 février 2018

Laravel Controller : How to use function store and create

I am currently new to laravel and working on a basic project where a service provider (SP) is able to post service details by filling up form.

enter image description here

I am trying to check if SP has uploaded a featured image. if yes, then rename file by using $featured = $request->featured; $featured_new_name = time().$featured->getClientOriginalName(); $featured->move('uploads/services', $featured_new_name); and saving it to 'uploads/services/' directory.

my ServiceController.php looks like this

public function store(Request $request)
{
      $this->validate($request, [
      'name' => 'required|max:255',
      'address' => 'required|max:255',
      'city' => 'required|max:255',
      'state' => 'required|max:255',
      'zipcode' => 'required|integer|digits:5',
      'category_id' => 'required',
      'workingday' => 'required',
      'content' => 'required'
      ]);
//checking if featured image (logo file) is uploaded or not 

    if($request->hasfile('featured'))
  {
    $featured = $request->featured;
    $featured_new_name = time().$featured->getClientOriginalName();
    $featured->move('uploads/services', $featured_new_name);
  }
  else {      }

     $featured->move('uploads/services', $featured_new_name);

      $service = Service::create([
      'name' => $request->name,
      'content' => $request->content,
      'address' => $request->address,
      'city' => $request->city,
      'state' => $request->state,
      'zipcode' => $request->zipcode,
      ]);

      if($request->hasfile('featured'))
      {
        $service = Service::create([
        'name' => $request->name,
        'content' => $request->content,
        'featured' =>'uploads/services/'.$featured_new_name,
        'address' => $request->address,
        'city' => $request->city,
        'state' => $request->state,
        'zipcode' => $request->zipcode,
    ]);
 }
    $service->workingdays()->attach($request->workingday);
    $service->categories()->attach($request->category_id);
    $service->user_id=auth()->id();
    $service->save();

  Session::flash('success','Service created successfully');
  return view('sp.services.create')->with('categories', Category::all())->with('workingday', Workingday::all());
}

I am saving logged in user_id along with all other service details. When user uploads logo file this code stores two records in database one with correct user_id and one with 0.

enter image description here

Here user_id 2 is correct entry. Please help me improve this code.

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire