One view set multible service types in Laravel

If you have a request to use the same functionality, same view, same fields, but different types of for example a type of service, you can use in laravel you are able to use just one view and add multiple services with it, as long as the fields and views are the same.

Lets do an example with it.

Let’s start with the View to see what we are actually doing and how this might look like:

This view shows the index, which contains a table and a button to add the session. I’ll show more views for the other CRUD below afterwards.

Notice: I also added a button, in the code which is not shown in the preview above.

@extends('layouts.app')
@section('content')
<div class="container">
   <h1>Group Session</h1>
<div class="row" id="service-info">
  <div class="col-lg-12">
     <h3>Add new Session:</h3>
     <div class="col-md-4">
        <a href="{{  action('GroupSessionController@create', $serviceType) 
}}" class="btn btn-block cleftButton-c service-add"> {{ $serviceType- 
>ServiceDesc }} </a>
      </div>
   </div>
</div>
<div class="row">
   <div class="col-md-12">
     <h3>All Group Sessions</h3>
     <table class="table table-hover" id="myTable">
        <thead>
           <th>id</th>
           <th>Host</th>
           <th>Session Data</th>
           <th>Behavior</th>
           <th>Type</th>
           <th>Edit</th>
           <th>Delete</th>
        </thead>
        <tbody>
@foreach ($sessions as $session)
           <tr>
              <td>{{ $session->id }}</td>
              <td><a href="{{ action('GroupSessionController@show', [$serviceType, $session->id]) }}">{{ $session->host}}</a></td>
              <td>{{ $session->date}}</td>
              <td>{{ $session->behavior}}</td>
              <td>{{ $session->type}}</td>
              <td>
                 <a href="{{ action('GroupSessionController@edit', [$serviceType, $session->id]) }}" class="btn btn-primary btn-xs">
                 <i class="fa fa-pencil" aria-hidden="true"></i> Edit
                 </a>
              </td>
              <td data-title="@lang('patient.delete')">
                 <form action="{!! action('GroupSessionController@destroy', [$serviceType, $session->id]) !!}" method="POST">
                    {{csrf_field()}}
                    {{ method_field('DELETE') }}
                    <a class="label label-danger" class="btn btn-danger btn-xs"><i class="fa fa fa-trash-o "></i>Delete</a>
                 </form>
              </td>
           </tr>
@endforeach
        </tbody>
     </table>
    </div>
  </div>
</div>
{{--ontainer--}}
@endsection

Next I wanna show, the migration so we know will what data we are dealing with.

For this I just need 2 tables one for the Service Type (ServiceType) and the other for the data to be added in the forms we provided in the create and edit views.

Add this to the migration file for the up method.

class CreateGroupSessionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('group_sessions', function (Blueprint $table) {
            $table->increments('id');
            $table->string('photo');
            $table->string('host');
            $table->dateTime('date');
            $table->string('behavior');
            $table->string('type');
            $table->unsignedSmallInteger('ServiceTypeId');
            $table->timestamps();
        });
    }
/* ... */

You also need a table where you store the different types for a table:

class CreateServicetypeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ServiceType', function (Blueprint $table) {
            $table->smallInteger('ServiceTypeId')->primary();
            $table->char('ServiceCode', 3);
            $table->string('ServiceDesc', 50);
            $table->boolean('Order');
        });
    }

Of course you need to do a model for the session groups

in the model of I named it GroupSession.php you can add a method to make a relationship of many to one, like this:

public function servicetype()
{
    return $this->belongsTo(ServiceType::class);
}

allso for the service type model which I named ServiceType.php you need to add a has many method

public function groupSessions()
{
    return $this->hasMany('App\GroupSession', 'ServiceTypeId', 'ServiceTypeId');
}

Before we come to the interesting part we need to add some routes. Which we can do in two ways, a resourceful router or we add routers individually.

in the example below I showed the resourceful router first and the other routers individually commented, so if you want to use them all you need to comment and adapted them for your project of course.

Route::resource('{serviceType}/groupSession', 'GroupSessionController');

//Route::get('/groupsession/{serviceType}', 'GroupSessionController@index');
//Route::get('/groupsession/{serviceType}/create', 'GroupSessionController@create');
//Route::get('/groupsession/{serviceType}/{groupSession}', 'GroupSessionController@show');
//Route::get('/groupsession/{serviceType}/{groupSession}/edit', 'GroupSessionController@edit');
//Route::put('/groupsession/{serviceType}/{groupSession}', 'GroupSessionController@update');
//Route::post('/groupsession/{serviceType}', 'GroupSessionController@store');
//Route::delete('/groupsession/{serviceType}/{groupSession}', 'GroupSessionController@destroy');

Now comes the interesting part, the Controller which defines the CRUD logic for this solution

Lets start with the index that we saw above, in the view example.

This function simple takes, the serviceType parameter and  uses it in a simple query in it. in this case also according to the route it adds the service type id to the URL.

public function index(ServiceType $serviceType)
{
    $sessions = GroupSession::where('ServiceTypeId' , $serviceType->ServiceTypeId)->get();

    return view('groupSession.index', compact('sessions', 'serviceType'));
}

The Create, looks looks this.

also very simple right?,  it also takes in the ServiceType and simply returns the create view and gives the serviceType along.

public function create(ServiceType $serviceType)
{
    return view('groupSession.create', compact('serviceType'));
}

The view could look this this.

you can add a h1 header to show the service type name in this case I named it ServiceDesc like this

<h1 style="margin-top: 110px;">Create {{ $serviceType->ServiceDesc }} - Group Session</h1>

then simple add the form as it is

<form id="create-form" action="{!! action('GroupSessionController@store', $serviceType) !!}" method="POST" enctype="multipart/form-data">
    {{ csrf_field() }}
        <section class="row">
            <div class="col-md-5">
                <div class="form-group">
                    Group photo
                    <br>
                    <input class="add-img" type="file" name="file" accept="image/x-png,image/gif,image/jpeg" required>
                    <br>
                </div>
            </div>
            <div class="col-md-7">
                <div class="form-group">
                     Host
                    <input name="host" type="text" class="form-control" id="host" required/>
                </div>
                <div class="form-group">
                    Session Date 
                    <input name="date" type="text" class="form-control datepicker-field" id="sessiondate" required/>
                </div>
                <div class="form-group">
                    Behavior
                    <select class="form-control" name="behavior" title="" required>
                        <option value=""></option>
                        <option value="option1">option1</option>
                        <option value="option2">option2</option>
                    </select>
                </div>
                <div class="form-group">
                    Type
                    <select class="form-control" name="type" title="" required>
                        <option value=""></option>
                        <option value="option1">option1</option>
                        <option value="option2">option2</option>
                        <option value="option3">option3</option>
                        <option value="option4">option4</option>
                    </select>
                </div>
            </div>
        </section>
        
        <section class="add-people row">
            <h4>Add Session Attendees</h4>
            <div class="people-container">
                <button class="add-new btn btn-success" type="button"><i class="fa fa-plus"></i> Add new Attendee</button>
            </div>
        </section>
    <hr>
    <input class="btn btn-success pull-right" type="submit"  />
</form>

To store this use a controller like this.

What I’ve done here is simply get the GroupSessionRequest and the ServiceType as a parameter. and returned a variable with the right query. also for the attendees as I have added this to the form above. you simple can use just the group session without the attendees.

public function store(GroupSessionRequest $request, ServiceType $serviceType)
{
    $groupSession = $serviceType->groupSessions()->create($request->all());

    $groupSession->sessionAttendee()->createMany($request->input('sessionAttende'));

    return redirect()->action('GroupSessionController@index', $serviceType);
}

Let’s continue with the edit

it’s almost the same as the create as always you just need to get the right id as well. so for a header you can also use it like this.

<h1>Edit {{ $serviceType->ServiceDesc }} - Group Session  - {{ $session->id }}</h1>

the form could look something like this.

<form action="{!! action('GroupSessionController@update', [$serviceType, $session->id]) !!}" method="POST" enctype="multipart/form-data">
    {{ csrf_field() }}
    {{ method_field('put') }}

    <section class="main-data row">
        <div class="col-md-5">
            <div class="form-group">
                Group photo:
                <br>
                <input type="file" name="file" accept="image/x-png,image/gif,image/jpeg">
                <br>
            </div>
        </div>
        <div class="col-md-7">
            <div >
                <div class="form-group">
                    Host:
                    <input name="host" type="text" class="form-control" id="host" value="{{ $session->host }}" />
                </div>
            </div>
            <div >
                <div class="form-group">
                    Session Date:
                    <input name="date" type="text" class="form-control datepicker-field" id="sessiondate" value="{{ $session->date }}" />
                </div>
            </div>
            <div >
                <div class="form-group">
                    Behavior:
                    <select class="form-control" name="behavior" title="" required>
                        <option value=""></option>
                        <option value="option" {{ $session->behavior === "option" ? 'selected' : '' }}>option</option>
                        <option value="option"{{ $session->behavior === "option" ? 'selected' : '' }}>option</option>
                    </select>
                </div>
            </div>
            <div >
                <div class="form-group">
                    Type:
                    <select class="form-control" name="type" title="" required>
                        <option value=""></option>
                        <option value="option" {{ $session->type === "option" ? 'selected' : '' }}>option</option>
                        <option value="option" {{ $session->type === "option" ? 'selected' : '' }}>option</option>
                        <option value="option" {{ $session->type === "option" ? 'selected' : '' }}>option</option>
                        <option value="option" {{ $session->type === "option" ? 'selected' : '' }}>option</option>
                    </select>
                </div>
            </div>
        </div>
    </section>

and the controller, like this.

public function edit(ServiceType $serviceType, GroupSession $groupSession){

    return view('groupSession.edit', ['session'=> $groupSession, 'serviceType' => $serviceType]);
}

also for the update method

public function update(GroupSessionRequest $request, ServiceType $serviceType, GroupSession $groupSession)
{
    // $groupSession = GroupSession::update($request->all());
    $groupSession->update($request->all());
    
    if($request->hasFile('file')){
        $media = MediaUploader::fromSource($request->file('file'))
            ->toDestination('local', "media/group_session")
            ->upload();
            
        $groupSession->attachMedia($media, 'groupsession');
    }

    foreach(request()->input('sessionAttende') as $id => $value){
        $sessionAttendee = SessionAttendee::find($id);
        
        if($sessionAttendee){
            $sessionAttendee->update($value);
        }else{
            $groupSession->sessionAttendee()->create($value);
        }
    }

at last the delete,

public function destroy(ServiceType $serviceType, GroupSession $groupSession){
$groupSession->delete(); FlashAlert::build('success', 'Session deleted successfully.'); return back(); 
}

One Reply to “One view set multible service types in Laravel”

  1. Greetings! I know this is kinda off topic nevertheless I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa?
    My site covers a lot of the same subjects as yours and
    I think we could greatly benefit from each other.
    If you might be interested feel free to send me an e-mail.
    I look forward to hearing from you! Great blog by the
    way! http://www.terracoat.biz/__media__/js/netsoltrademark.php?d=918.network%2Fcasino-games%2F74-mega888

Leave a Reply

Your email address will not be published.