Insert/Create – Laravel

Insert or Create new data is easy on laravel. To insert we must take care of following things:

  • Controller ===> create() function load the selected form from where the data can be inserted
  • Views ===> Insert form
  • Controller ===> Store() function which validates the data and stores accordingly. There are 2 ways to store the data
    • One by one 
    • Bulk data saving. For bulk, protected $fillable must be declared inside model   

Controller ===> Create Function

public function create()
    {
        $title = "..:::: Benera Pty. Ltd. - Testimonial Create";
        $update = false;
        return view('backend.testimonial-create',compact('title','update'));
    }

Views ===> Create Form

<div class="form-group">
	<label class="col-sm-5 control-label no-padding-right" for="form-field-1">Address/Designation</label>
	<div class="col-sm-7">
		<input name="address_designation" value="{{ old('address_designation') }}" type="text" />
	</div>
</div>

<div class="form-group">
	<label class="col-sm-5 control-label no-padding-right" for="form-field-1">Testimonial</label>
	<div class="col-sm-7">
		<textarea name="testimonial"   />{{ old('testimonial') }}  </textarea>
	</div>
</div>

Controller ===> Store

public function store(Request $request)
    {

     $data = $request->validate([
         'status'=>'required',
         'name'=>'required|max:20',
         'address_designation'=>'required|max:20',
         'testimonial'=>'required|min:5|max:200',

     ],[
         'name.max' => "Name must not exceed 10 character",
         'address_designation.max' => "Address/Designation must not exceed 10 character",
         'testimonial.max' => "Testimonial must be written in between 5 to 200 characters",
     ]);


     if($request->hasFile('image'))
     {
        //$oldFilePath = $slider->image1_file;
         
        ///unlink(public_path().'/'.$oldFilePath);
        // $data['image'] = $this->uploadFile($request->file('image'),'')); // To Local public folder
         $data['image'] = $this->uploadFile($request->file('image'),'img/testimonial'); // To Storage folder inside given path
         //$data['image'] = $this->uploadFile($request->file('image'),app_path('img/testimonial/')); // To Any Folder we choose from root project folder


     }
   
     $testimonial = new Testimonial;

     $testimonial->create($data);

     return redirect()->back()->withSuccess("Testimonial inserted successfully");
    }

Leave a Reply

Your email address will not be published. Required fields are marked *