queu's avatar
Level 1

How to do file upload using laraval HTML/Collection

How should I approach implementing a image upload feature using laraval HTML/Collection.

I created a macro

<?php

Form::macro('myInput', function($type="text", $name, $label="", $options=[], $default = null)
{
    $label = ($label =='') ? '' : html_entity_decode(Form::label($name, $label));
    return "
        <div class='form-group'>
            ". $label . 
              Form::input($type, $name, $default, array_merge(["class" => "form-control"], $options)). "
        </div>
    ";
});

Form::macro('mySelect', function($name, $label="", $values=[], $selected=null, $options=[])
{
    $label = ($label =='') ? '' : html_entity_decode(Form::label($name, $label));
    return "
        <div class='form-group'>
            ". $label . 
              Form::select($name, $values, $selected,array_merge(["class" => "form-control"], $options)). "
        </div>
    ";
});

Form::macro('myFile', function($name, $label="", $options=[])
{
    $label = ($label =='') ? '' : html_entity_decode(Form::label($name, $label));
    return "
        <div class='form-group'>
            ". $label . 
              Form::file($name, array_merge(["class" => "form-control"], $options)). "
        </div>
    ";
});

Form::macro('myTextArea', function($name, $label="", $options=[], $default = null)
{
    $label = ($label =='') ? '' : html_entity_decode(Form::label($name, $label));
    return "
        <div class='form-group'>
            ". $label . 
              Form::textarea($name, $default, array_merge(["class" => "form-control", "rows"=> 3], $options)). "
        </div>
    ";
});

Form::macro('myCheckbox', function($name, $label="", $value='', $checked='', $options=[])
{
    // $label = ($label =='') ? '' : html_entity_decode(Form::label($name, $label));
    return "
        <div class='checkbox'>
            <label>" . 
                Form::checkbox($name, $value, $checked, $options) . $label . "
            </label>
        </div>
    ";
});

Form::macro('myRange', function($name, $start, $end, $selected='', $options=[])
{
    return "
        <div class='form-group'>
            " . Form::selectRange($name, $start, $end, $selected,array_merge(["class" => "form-control"], $options)). "
        </div>
    ";
});

This is how the form looks

<div class="row mB-40">
    <div class="col-sm-8">
        <div class="bgc-white p-20 bd">
            
                {!! Form::myInput('name', 'name', 'Name') !!}

                {!! Form::myInput('email', 'email', 'Email') !!}
        
                {!! Form::myInput('phone', 'phone', 'Contact') !!}

                {!! Form::myInput('opening_hours', 'opening_hours', 'Opening Hours') !!}

                {!! Form::myInput('closing_hours', 'closing_hours', 'Closing Hours') !!}

                {!! Form::myInput('business_days', 'business_days', 'Business Days') !!}

                {{-- {!! Form::myFile('mime', 'Institition Image') !!} --}}
        
                {{-- {!! Form::myTextArea('bio', 'Bio') !!} --}}
        </div>  
    </div>
</div>

This is how my Controller looks


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;

use App\MedicalInstitution;
use App\User;
use Auth;
use Session;



class MedicalInstitutionController extends Controller
{


    public function __construct() {
        $this->middleware(['auth', 'clearance'])->except('index', 'show');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
       // $institutions = MedicalInstitution::all(); // ->paginate(5) show only 5 items at a time in descending order
       $user_id = Auth::user()->id; // *Explain ->id*
       $user_id = Auth::id();

       // $institutions = DB::table('medical_institutions')->where('user_id', $user);
       // $institutions = $user->where('user_id', $user);

       // $institutions = $user->medical_institutions;
       // $institutions = DB::table('medical_institutions')-get();
       $institutions = MedicalInstitution::where('user_id', $user_id)->get();
       // echo print_r($user_id);
       // print_r($institutions);
    //    return $user->medical_institutions;
       
       return view('admin.institutions.index', compact('institutions'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.institutions.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request , [
            'name'=>'required|max:300',
            'email'=>'required',
            'phone'=>'required',
            'opening_hours'=>'required',
            'closing_hours'=>'required',
            'business_days'=>'required',
            // 'institution_image'=>'required|file|1024',
        ]);

        $path = $request->file('image')->store('upload');

        // $user = auth()->user();
        // Get current usrer
        $user = Auth::user();
        // Get all values entered
        $institution = $request->all();
        // assign user_id to institution created
        $institution['user_id'] = $user->id;
        // 
        $user->medical_institutions()->create($institution);

        // $name = $request['name'];
        // $email = $request['email'];
        // $phone = $request['phone'];


        // $institution = MedicalInstitution::create($request->only('name', 'email', 'phone'));

        return redirect()->route('admin.institutions.index')->with('flash_message', 
        'Medical Institution  '.$institution['name']. '  created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $institution = MedicalInstitution::findOrFail($id); // Find MedicalInstitution of id = $id

        return view('admin.institutions.show', compact('institution'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $institution = MedicalInstitution::findOrFail($id);

        return view('institutions.edit', compact('institution'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name'=>'required|max:300',
            'email'=>'required',
            'phone'=>'required',
            'opening_hours'=>'required',
            'closing_hours'=>'required',
            'business_days'=>'required',
        ]);


        $institution = MedicalInstitution::findOrFail($id);

        $institution->name = $request->input('name');
        $institution->email = $request->input('email');
        $institution->phone = $request->input('phone');
        $institution->opening_hours = $request->input('opening_hours');
        $institution->closing_hours = $request->input('closing_hours');
        $institution->business_days = $request->input('business_days');

        $institution->save();


        return redirect()->route('institutions.show', $institution->id)->with('flash_message', 
        'Medical Institution, '. $institution->title.' updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $institution = MedicalInstitution::findOrFail($id);
        $institution->delete();


        return redirect()->route('institutions.index')
            ->with('flash_message',
             'Medical Institution successfully deleted');
    }
}

0 likes
3 replies
bobbybouwmann's avatar

What is your question? Does the upload part not work?

In general when you use Html/Form builder you need to things to handle uploads. The first one is that your inputs need to be wrapped in a from and you also need to make sure you tell the form that it should be posting files/images. Also don't forget to close the form!

{!! Form::open(['url' => 'foo/bar', 'files' => true]) }}!

// Your inputs

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

Documentation: https://laravelcollective.com/docs/master/html#opening-a-form

Now the second part is that the name of the input needs to match in your controller. In your controller you specify a file input with the name mime, but in your controller you name image.

As far as I know that should fix it all!

queu's avatar
Level 1

@bobbybouwmann Sorry for not being explicit enough. The issue is that I am not sure how to implement the upload feature with the HTML/FORM package by building the custom form macros that I have created.

bobbybouwmann's avatar

Well like I said. You just need to make sure your Form understands that it needs to post files/images. After that you only need the file input. Your controllers looks right to me. Just make sure all the names match up!

Do you have a specific question now?

Please or to participate in this conversation.