Обновление изображения обнуляется Laravel - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь обновить изображение в laravel с помощью Yajra DataTabel, когда я вставляю изображение в базу данных и папку, кажется, что он работает нормально, потому что он хранится в папке и отображается в таблице данных yajra, но когда я редактировать изображение, оно не показывает изображение и не хранится в базе данных. В любом случае это мой код. Заранее спасибо

Контроллер:

public function edit($id)
{
    if (request()->ajax()) {
        $shippings = Shipping_data::findOrFail($id);
        return response()->json(['result' => $shippings]);
    }
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request)
{
    $shippingReceipt_name = $request->hidden_shippingReceipt;
    $shippingReceipt = $request->file('shippingReceipt');
    if($shippingReceipt != ''){
        $rules = array(
        'name' ,
        'mobile',
        'items',
        'shippingAddress',
        'amount',
        'facebookLink',
        'facebookName',
        "modePayment",
        "shipVia"=> 'required',
        "trackingNumber"=> 'required',
        "shippingReceipt" => 'required',
        "shippingCharged"=> 'required',
        "shippingWeight"=> 'required'
    );
     $error = Validator::make($request->all(), $rules);
        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $shippingReceipt_name = rand() . '.' . $shippingReceipt->getClientOriginalExtension();
        $shippingReceipt->move(public_path('receipt'), $shippingReceipt_name);
    } 
     else {
         $rules = array(
        'name' ,
        'mobile',
        'items',
        'shippingAddress',
        'amount',
        'facebookLink',
        'facebookName',
        "modePayment",
        "shipVia"=> 'required',
        "trackingNumber"=> 'required',
        "shippingReceipt" => 'required',
        "shippingCharged"=> 'required',
        "shippingWeight"=> 'required',
    );

      $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }
    }

    $form_data = array(
        'name' => $request->name,
        'mobile'=> $request->mobile,
        'items'=> $request->items,
        'shippingAddress'=> $request->shippingAddress,
        'amount'=> $request->amount,
        'facebookLink'=> $request->facebookLink,
        'facebookName'=> $request->facebookName,
        "modePayment"=> $request->modePayment,
        "shipVia"=> $request->shipVia,
        "trackingNumber"=> $request->trackingNumber,
        "shippingReceipt"=> $shippingReceipt_name,
        "shippingWeight"=> $request->shippingWeight,
        "shippingCharged"=> $request->shippingCharged,
    );

    Shipping_data::whereId($request->hidden_id)->update($form_data);

    return response()->json(['success' => 'Shipping Data is successfully updated']);
}

blade. php:

  <form method="post" id="shipping_form" class="form-horizontal" enctype='multipart/form-data'>
                @csrf
                @if(Auth::check() && Auth::user()->role == "admin")
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" placeholder="Please Enter Client Name"
                        id="name">
                    </select>
                </div>
                <div class="form-group">
                    <label>Mobile</label>
                    <input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
                        id="mobile">
                </div>
                <div class="form-group">
                    <label>Items Order</label>
                    <input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
                        id="items">
                </div>
                <div class="form-group">
                    <label>Shipping Address</label>
                    <input type="text" class="form-control" name="shippingAddress" id="shippingAddress"
                        placeholder="Please Enter Shipping Address">
                </div>
                <div class="form-group">
                    <label>Amount</label>
                    <input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
                        id="amount">
                </div>
                <div class="form-group">
                    <label>Facebook Link</label>
                    <input type="text" class="form-control" name="facebookLink" id="facebookLink"
                        placeholder="Please Enter Facebook Link">
                </div>
                <div class="form-group">
                    <label>Facebook Name</label>
                    <input type="text" class="form-control" name="facebookName" id="facebookName"
                        placeholder="Please Enter Facebook Name">
                </div>

                <div class="form-group">
                    <label>Mode of Payment</label>
                    <input type="text" class="form-control" name="modePayment" id="modePayment"
                        placeholder="Please Enter Mode of Payment">
                </div>
                @endif
                @if(Auth::check() && Auth::user()->role == "employee")
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" placeholder="Please Enter Name" id="name"
                        READONLY>
                </div>
                <div class="form-group">
                    <label>Mobile</label>
                    <input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
                        id="mobile" READONLY>
                </div>
                <div class="form-group">
                    <label>Items Order</label>
                    <input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
                        id="items" READONLY>
                </div>
                <div class="form-group">
                    <label>Shipping Address</label>
                    <input type="text" class="form-control" name="shippingAddress" id="shippingAddress" READONLY
                        placeholder="Please Enter Shipping Address">
                </div>
                <div class="form-group">
                    <label>Amount</label>
                    <input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
                        id="amount" READONLY>
                </div>
                <div class="form-group">
                    <label>Facebook Link</label>
                    <input type="text" class="form-control" name="facebookLink" id="facebookLink" READONLY
                        placeholder="Please Enter Facebook Link">
                </div>
                <div class="form-group">
                    <label>Facebook Name</label>
                    <input type="text" class="form-control" name="facebookName" id="facebookName" READONLY
                        placeholder="Please Enter Facebook Name">
                </div>

                <div class="form-group">
                    <label>Mode of Payment</label>
                    <input type="text" class="form-control" name="modePayment" id="modePayment" READONLY
                        placeholder="Please Enter Mode of Payment">
                </div>
                @endif
                <div class="form-group">
                    <label>Shipping Via</label>
                    <input type="text" class="form-control" name="shipVia" placeholder="Please Enter Shipping Via"
                        id="shipVia">
                </div>
                <div class="form-group">
                    <label>Tracking Number</label>
                    <input type="text" class="form-control" name="trackingNumber" id="trackingNumber"
                        placeholder="Please Enter Tracking Number">
                </div>
                <div class="form-group">
                    <label>Shipping Receipt</label>
                    <br>
                    <input type="file" class="form-control file-form" name="shippingReceipt" id="shippingReceipt">
                </div>
                <div class="form-group">
                    <label>Shipping Charged</label>
                    <input type="text" class="form-control" name="shippingCharged" id="shippingCharged"
                        placeholder="Please Enter Shipping Charged">
                </div>
                <div class="form-group">
                    <label>Shipping Weight</label>
                    <input type="text" class="form-control" name="shippingWeight" id="shippingWeight"
                        placeholder="Please Enter Shipping Weight">
                </div>

                <br />
                <div class="form-group" align="center">
                    <input type="hidden" name="action" id="action" value="Add" />
                    <input type="hidden" name="hidden_id" id="hidden_id" />
                    <input type="submit" name="action_button" id="action_button" class="btn btn-success"
                        value="Add" />
                </div>
            </form>

Маршрут:

Route::resource('shipping', 'ShippingController');

Route::post('shipping/update', 'ShippingController@update')->name('shipping.update');

это мой результат при использовании dd:

array:15 [
  "_token" => "lxEGrS8FOvM4zeuqGSJSSjNEhjexj3TkvM11JDCv"
  "name" => "Alif Khan"
  "mobile" => "9293000245"
  "items" => "Nike Men's T-Shirt"
  "shippingAddress" => "#8D Barcelona"
  "amount" => "100"
  "facebookLink" => "https://www.facebook.com/123"
  "facebookName" => "Mohammad Khan"
  "modePayment" => "GCash"
  "shipVia" => "12"
  "trackingNumber" => "12"
  "shippingCharged" => "12"
  "shippingWeight" => "12"
  "action" => "Edit"
  "hidden_id" => "2"
];

Модель:

1 Ответ

0 голосов
/ 15 июля 2020

Вы определили маршруты ресурсов, которые по умолчанию определяют несколько маршрутов и методов для тех, что подробно описаны здесь . Также вы определили дополнительный маршрут для использования того же кода, что и метод Route::resource route PATCH с маршрутом с именем shipping.update. Обратите внимание, что определение дополнительного маршрута отменяет определение метода POST маршрутов ресурсов. Вы можете удалить строку Route::post('shipping/update', 'ShippingController@update')->name('shipping.update'); из ваших маршрутов, если она связана только с обновлением текущих данных.

// РЕДАКТИРОВАТЬ, вы также можете вставить сейчас

Вы можете использовать это как свой модальный шаблон для обновления данных:

<form method="POST" action="{{route('shipping.update',$data->id)}}" id="shipping_form" class="form-horizontal" enctype='multipart/form-data'>
    @csrf
    @method('PUT')
    @if(Auth::check() && Auth::user()->role == "admin")
    <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" placeholder="Please Enter Client Name"
            id="name" @isset($data) value="{{$data->name}}"@endisset>
        </select>
    </div>
    <div class="form-group">
        <label>Mobile</label>
        <input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
            id="mobile" @isset($data) value="{{$data->mobile}}"@endisset>
    </div>
    <div class="form-group">
        <label>Items Order</label>
        <input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
            id="items" @isset($data) value="{{$data->items}}"@endisset>
    </div>
    <div class="form-group">
        <label>Shipping Address</label>
        <input type="text" class="form-control" name="shippingAddress" id="shippingAddress"
            placeholder="Please Enter Shipping Address" @isset($data) value="{{$data->shippingAddress}}"@endisset>
    </div>
    <div class="form-group">
        <label>Amount</label>
        <input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
            id="amount" @isset($data) value="{{$data->amount}}"@endisset>
    </div>
    <div class="form-group">
        <label>Facebook Link</label>
        <input type="text" class="form-control" name="facebookLink" id="facebookLink"
            placeholder="Please Enter Facebook Link" @isset($data) value="{{$data->facebookLink}}"@endisset>
    </div>
    <div class="form-group">
        <label>Facebook Name</label>
        <input type="text" class="form-control" name="facebookName" id="facebookName"
            placeholder="Please Enter Facebook Name" @isset($data) value="{{$data->facebookName}}"@endisset>
    </div>

    <div class="form-group">
        <label>Mode of Payment</label>
        <input type="text" class="form-control" name="modePayment" id="modePayment"
            placeholder="Please Enter Mode of Payment" @isset($data) value="{{$data->modePayment}}"@endisset>
    </div>
    @endif
    @if(Auth::check() && Auth::user()->role == "employee")
    <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" placeholder="Please Enter Name" id="name"
            READONLY @isset($data) name="{{$data->name}}"@endisset>
    </div>
    <div class="form-group">
        <label>Mobile</label>
        <input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
            id="mobile" READONLY @isset($data) value="{{$data->mobile}}"@endisset>
    </div>
    <div class="form-group">
        <label>Items Order</label>
        <input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
            id="items" READONLY @isset($data) value="{{$data->items}}"@endisset>
    </div>
    <div class="form-group">
        <label>Shipping Address</label>
        <input type="text" class="form-control" name="shippingAddress" id="shippingAddress" READONLY
            placeholder="Please Enter Shipping Address" @isset($data) value="{{$data->shippingAddress}}"@endisset>
    </div>
    <div class="form-group">
        <label>Amount</label>
        <input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
            id="amount" READONLY @isset($data) value="{{$data->amount}}"@endisset>
    </div>
    <div class="form-group">
        <label>Facebook Link</label>
        <input type="text" class="form-control" name="facebookLink" id="facebookLink" READONLY
            placeholder="Please Enter Facebook Link" @isset($data) value="{{$data->facebookLink}}"@endisset>
    </div>
    <div class="form-group">
        <label>Facebook Name</label>
        <input type="text" class="form-control" name="facebookName" id="facebookName" READONLY
            placeholder="Please Enter Facebook Name" @isset($data) value="{{$data->facebookName}}"@endisset>
    </div>

    <div class="form-group">
        <label>Mode of Payment</label>
        <input type="text" class="form-control" name="modePayment" id="modePayment" READONLY
            placeholder="Please Enter Mode of Payment" @isset($data) value="{{$data->modePayment}}"@endisset>
    </div>
    @endif
    <div class="form-group">
        <label>Shipping Via</label>
        <input type="text" class="form-control" name="shipVia" placeholder="Please Enter Shipping Via"
            id="shipVia" @isset($data) value="{{$data->shipVia}}"@endisset>
    </div>
    <div class="form-group">
        <label>Tracking Number</label>
        <input type="text" class="form-control" name="trackingNumber" id="trackingNumber"
            placeholder="Please Enter Tracking Number" @isset($data) value="{{$data->trackingNumber}}"@endisset>
    </div>
    <div class="form-group">
        <label>Shipping Receipt</label>
        <br>
        <input type="file" class="form-control file-form" name="shippingReceipt" id="shippingReceipt">
         @if(isset($data) && !empty($data->shippingReceipt))
             <a href="{{url('/receipt/'.$data->shippingReceipt)}}">Receipt</a>
         @endif
    </div>
    <div class="form-group">
        <label>Shipping Charged</label>
        <input type="text" class="form-control" name="shippingCharged" id="shippingCharged"
            placeholder="Please Enter Shipping Charged" @isset($data) value="{{$data->shippingCharged}}"@endisset>
    </div>
    <div class="form-group">
        <label>Shipping Weight</label>
        <input type="text" class="form-control" name="shippingWeight" id="shippingWeight"
            placeholder="Please Enter Shipping Weight" @isset($data) value="{{$data->shippingWeight}}"@endisset>
    </div>

    <br />
    <div class="form-group" align="center">
        <input type="hidden" name="action" id="action" value="Edit" />
        <input type="hidden" name="hidden_id" id="hidden_id" @isset($data) value="{{$data->hidden_id}}"@endisset />
        <input type="submit" name="action_button" id="action_button" class="btn btn-success"
            value="Save" />
    </div>
</form>

В методе контроллера edit вы можете вернуть представление лезвия с данными:

$data = Shipping_data::findOrFail($id);
return view('this.template',array('data' => $data));

, а в методе контроллера create вы можете вернуть просмотр без данных:

return view('this.template');

Ваш контроллер должен быть настроен следующим образом:

public function create(Request $request){// shipping.create route for returning template to create new data
    return view('shipping.create');
}

public function edit($id){// route shipping.edit get existing data to be edited
    return view('shipping.edit',array('data' => Shipping_data::findOrFail($id)));
}

public function store(Request $request){//route shipping.store this is for creating and storing new data
    
}

public function update(Request $request, $id)//route shipping.update 
{
    if($request->hasFile('shippingReceipt')){//check if request has file attached
        $shippingReceipt_name = $request->hidden_shippingReceipt;
        $shippingReceipt = $request->file('shippingReceipt');
        $rules = array(
            'name' ,
            'mobile',
            'items',
            'shippingAddress',
            'amount',
            'facebookLink',
            'facebookName',
            "modePayment",
            "shipVia"=> 'required',
            "trackingNumber"=> 'required',
            "shippingReceipt",//don't require the receipt on edit
            "shippingCharged"=> 'required',
            "shippingWeight"=> 'required'
        );
        $validator = Validator::make($request->all(), $rules);
        if($validator->fails()){
            return response()->json(['errors' => $validator->errors()->all()]);
        }

        $shippingReceipt_name = rand() . '.' . $shippingReceipt->getClientOriginalExtension();
        $shippingReceipt->move(public_path('receipt'), $shippingReceipt_name);
    } else {
         $rules = array(
        'name' ,
        'mobile',
        'items',
        'shippingAddress',
        'amount',
        'facebookLink',
        'facebookName',
        "modePayment",
        "shipVia"=> 'required',
        "trackingNumber"=> 'required',
        "shippingReceipt",//don't require the receipt on edit
        "shippingCharged"=> 'required',
        "shippingWeight"=> 'required',
    );

      $validator = Validator::make($request->all(), $rules);

        if($validator->fails())
        {
            return response()->json(['errors' => $validator->errors()->all()]);
        }
    }

    $shipping_data = Shipping_data::whereId($id)->first();//get the eloquent model with corresponding data
    $shipping_data->name = $request->name;
    $shipping_data->mobile = $request->mobile;
    $shipping_data->items = $request->items;
    $shipping_data->shippingAddress = $request->shippingAddress;
    $shipping_data->amount = $request->amount;
    $shipping_data->facebookLink = $request->facebookLink;
    $shipping_data->facebookName = $request->facebookName;
    $shipping_data->modePayment = $request->modePayment;
    $shipping_data->shipVia = $request->shipVia;
    $shipping_data->trackingNumber = $request->trackingNumber;
    $shipping_data->shippingReceipt = isset($shippingReceipt_name) ?  $shippingReceipt_name : $shipping_data->shippingReceipt;
    $shipping_data->shippingWeight = $request->shippingWeight;
    $shipping_data->shippingCharged = $request->shippingCharged;
    $shipping_data->save();// save the data into the database

    return redirect()->route('shipping.index');
}

Модель:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shipping_data extends Model
{
    protected $fillable = ['name', 'mobile', 'items', 'shippingAddress', 'amount',
    'facebookLink', 'facebookName', "modePayment", "shipVia", "trackingNumber", "shippingReceipt","shippingCharged","shippingWeight"];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...