1

Tenho uma collection na variável $paymentMethods com formas de pagamento:

inserir a descrição da imagem aqui

E tenho outra collection na variável $timelines que tem um relacionamento Many to Many com as formas de pagamento. Preciso listar na view em um select as formas de pagamento disponiveis e marcar as selecionadas. Com o que fiz as formas de pagamento disponiveis se repetem e são marcadas as formas de pagamento de todas as timelines.

Controller:

namespace App\Http\Controllers;

use App\Timeline;
use App\Order;
use App\PaymentMethod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TimelineController extends Controller
{

public function indexCustomer($order, $supplier)
{
    $user = Auth::user();
    $typeUser = $user->userable_type;
    $order = Order::find($order);
    $paymentMethods = PaymentMethod::all();
    $paymentMethodsOrder = $order->paymentMethods->map(function ($item, $key) {
        return $item['name'];
    })->toArray();

    $timelines = Timeline::where('order_id', $order->id)->where('supplier_id', $supplier)->get();

    return view('customer.order.timeline')
        ->with('order', $order)
        ->with('paymentMethods', $paymentMethods)
        ->with('paymentMethodsOrder', $paymentMethodsOrder)
        ->with('timelines', $timelines)
        ->with('supplier', $supplier);
}

public function storeCustomer(Request $request, $order, $supplier)
{
    $user = Auth::user();
    $typeUser = $user->userable_type;
    $order = Order::find($order);
    $paymentMethods = PaymentMethod::all();
    $paymentMethodsOrder = $order->paymentMethods->map(function ($item, $key) {
        return $item['name'];
    })->toArray();

    $timeline = new Timeline;
    $timeline->user_id = $user->id;
    $timeline->order_id = $order->id;
    $timeline->customer_id = $user->userable->id;
    $timeline->supplier_id = $supplier;
    $timeline->status = $request->status;
    $priceAverage = str_replace('.', '', $request->price_average);
    $priceAverage = str_replace(',', '.', $priceAverage);
    $priceAverage = floatval($priceAverage);
    $timeline->price_average = $priceAverage;
    $timeline->description = $request->description;
    $timeline->save();

    $timelines = Timeline::where('order_id', $order->id)->where('supplier_id', $supplier)->get();

    return view('customer.order.timeline')
        ->with('order', $order)
        ->with('paymentMethods', $paymentMethods)
        ->with('paymentMethodsOrder', $paymentMethodsOrder)
        ->with('timelines', $timelines)
        ->with('supplier', $supplier);
}

public function indexSupplier($order)
{
    $user = Auth::user();
    $typeUser = $user->userable_type;
    $order = Order::find($order);
    $paymentMethods = PaymentMethod::all();
    $paymentMethodsOrder = $order->paymentMethods->map(function ($item, $key) {
        return $item['id'];
    })->toArray();

    $timelines = Timeline::where('order_id', $order->id)->where('supplier_id', $user->userable->id)->get();

    return view('supplier.order.timeline')
        ->with('order', $order)
        ->with('paymentMethods', $paymentMethods)
        ->with('paymentMethodsOrder', $paymentMethodsOrder)
        ->with('timelines', $timelines);

}


public function storeSupplier(Request $request, $order)
{
    $user = Auth::user();
    $typeUser = $user->userable_type;
    $order = Order::find($order);
    if (Timeline::activeSupplierOrder($user->userable->id)->count() == 0) {
        $order->suppliers()->attach($user->userable->id);
    }
    $paymentMethods = PaymentMethod::all();
    $paymentMethodsOrder = $order->paymentMethods->map(function ($item, $key) {
        return $item['name'];
    })->toArray();

    $timeline = new Timeline;
    $timeline->user_id = $user->id;
    $timeline->order_id = $order->id;
    $timeline->supplier_id = $user->userable->id;
    $timeline->customer_id = $order->user->userable->id;
    $timeline->status = $request->status;
    $priceAverage = str_replace('.', '', $request->price_average);
    $priceAverage = str_replace(',', '.', $priceAverage);
    $priceAverage = floatval($priceAverage);
    $timeline->price_average = $priceAverage;
    $timeline->description = $request->description;
    $timeline->save();

    foreach ($request->payment_methods as $paymentMethodId) {
        $timeline->paymentMethods()->attach($paymentMethodId);
    }

    $timelines = Timeline::where('order_id', $order->id)->where('supplier_id', $user->userable->id)->get();

    return view('supplier.order.timeline')
        ->with('timelines', $timelines)
        ->with('order', $order)
        ->with('paymentMethods', $paymentMethods)
        ->with('paymentMethodsOrder', $paymentMethodsOrder);

}
}

View:

@extends('customer.app')
@section('title', 'Histórico')
@section('content')
<div class="row">
<div class="col-sm-12">
    <div class="timeline">

        <article class="timeline-item alt">
            <div class="text-right">
                <div class="time-show">
                    <a href="#" class="btn btn-custom w-lg">Histórico</a>
                </div>
            </div>
        </article>

        @foreach($timelines as $timeline)
            <article class="timeline-item @if($timeline->user_id == Auth::user()->id) alt @else "" @endif">
                <div class="timeline-desk">
                    <div class="panel m-t-20 m-b-20">
                        <div class="panel-body">
                            <span class="arrow-alt"></span>
                            <span class="timeline-icon bg-info"><i class="zmdi zmdi-circle"></i></span>
                            <p class="timeline-date text-muted"><small>{{ date( 'd/m/Y H:i' , strtotime($timeline->created_at)) }}</small></p>
                            <p class="m-t-10">Status: {{ $timeline->status }}</p>
                            @isset($timeline->price_average)
                                <p class="m-t-10">Valor: R$ {{ number_format($timeline->price_average, 2, ',', '.') }}</p>
                            @endisset
                            @isset($timeline->price_average)
                                @foreach($timeline->paymentMethods as $paymentMethod)
                                    <p class="m-t-10">{{ $paymentMethod['name'] }}</p>
                                @endforeach
                            @endisset
                            <p class="m-t-10">{{ $timeline->description }}</p>
                            <div class="btn-group dropup @if($timeline->user_id == Auth::user()->id) pull-right @else pull-left @endif m-t-10">
                                <a type="button" class="btn btn-primary" href="#" data-toggle="modal" data-target="#con-close-modal">Responder</a>
                            </div>
                        </div>
                    </div>
                </div>
            </article>
        @endforeach
    </div>
</div>
</div>

<!-- Modal -->
<div id="con-close-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<form class="form-horizontal" method="POST" action="{{ route('customer.timelines.store', ['order' => $order, 'supplier' => $supplier]) }}">
    {{ csrf_field() }}
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title">{{ $order->category->name }}</h4>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="control-label m-b-10" style="text-align: left">Você aprova o valor de R$ {{ number_format($timeline->price_average, 2, ',', '.') }} e as condições de pagamento proposto pela banda ou quer fazer uma contraproposta?</label>
                            <select class="form-control" id="status" name="status">
                                <option value="">Selecione</option>
                                <option value="Aprovado">Aprovado</option>
                                <option value="Contraproposta">Contraproposta</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div id="price-average-div">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="control-label">Informe um valor em reais para contraproposta:</label>
                                <input type="text" class="form-control" id="price-average" name="price_average" value="{{ $timeline->price_average }}">
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('payment_methods') ? ' has-error' : '' }}">
                            <div class="col-md-9">
                                <label for="payment_methods">Formas de Pagamento<h6>Selecione as formas de pagamento oferecidas.</h6></label>
                                <select multiple class="form-control" name="payment_methods[]" required>
                                    @foreach($paymentMethods as $paymentMethod)
                                        <option {{ $paymentMethod->id == 3 ? 'selected' : '' }} value="{{ $paymentMethod->id }}">{{ $paymentMethod->name }}</option>
                                    @endforeach
                                </select>
                                @if ($errors->has('payment_methods'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('payment_methods') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group no-margin">
                            <label class="control-label">Observações:</label>
                            <textarea name="description" class="form-control autogrow" style="overflow: hidden; word-wrap: break-word; resize: horizontal; height: 104px;">{{ $timeline->description }}</textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Fechar</button>
                <button type="submit" class="btn btn-primary waves-effect waves-light warning-alert-interest">Enviar</button>
            </div>
        </div>
    </div>
</form>
</div>
@endsection

@push('scripts')
<script src="{{ asset('assets/js/jquery.mask.js') }}"></script>
<script>
$(document).ready(function(){
    $('#price-average').mask('000.000,00', {reverse: true});
});
</script>
@endpush

View com formas de pagamento repetidas e selecionadas as opções de pagamento de todas as timelines:

inserir a descrição da imagem aqui

1 Resposta 1

1

easy:

1.

troca os trechos: $paymentMethods = PaymentMethod::all(); $paymentMethodsOrder = $order->paymentMethods->map(function ($item, $key) { return $item['id']; })->toArray();

por: $paymentMethods = PaymentMethod::pluck('name', 'id'); $paymentMethodsOrder = $order->paymentMethods->pluck('id')->toArray();

2.

usando (https://laravelcollective.com/docs/5.3/html#drop-down-lists) troca seu < select > por: Form::select('payment_methods[]', $paymentMethods, $paymentMethodsOrder, ['multiple', 'class' => 'form-control', 'required']);

OBS: outra coisa dá uma olhada sobre (https://laravel.com/docs/5.3/eloquent-mutators) pra dar uma limpada nesse código, também dá uma olhada sobre o ->fill().

9
  • Como ficaria sem o laravel collective?
    – Marcelo
    Commented 13/12/2017 às 0:14
  • Outra coisa, quero comparar o $paymentsMethods com $timelines sendo que cada timeline tem um many to many com a classe PaymentMethods e não com a $paymentsMethodsOrder
    – Marcelo
    Commented 13/12/2017 às 0:23
  • instalação collective: laravelcollective.com/docs/5.3/html#installation para usar nos formularios, já faz os bindings pra vc Commented 13/12/2017 às 0:37
  • então sua Timeline tem q ter o relacionamento com PaymentMethod Commented 13/12/2017 às 0:40
  • Ja usei laravel collective e não gostei. A timeline tem o relacionamento com PaymentMethod. Creio que dessa forma não vai ter como fazer, no caso quando clico em um botão que tem os dados abre um modal que tem essa view. Tenho que passar os dados que já estão no card para esse modal.
    – Marcelo
    Commented 13/12/2017 às 0:45

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .