Столбцы не обновляются в Laravel - PullRequest
0 голосов
/ 15 января 2020

В моей таблице есть столбцы, которые не обновляются. Я проверял все много раз, и все написано правильно и должно работать.

У меня есть следующее на мой взгляд:

@section('content')

  {{ csrf_field() }}


  <h1 class='py-3'>List of Providers</h1>


  <div class='form-group'>
    <textarea  name='survey_providers_list' type='' rows='10' class='form-control' id='' value = '{{ old('survey_providers_list') }}'></textarea>
    <div>{{ $errors->first('survey_providers_list') }}</div>
  </div>

  <h1 class='py-3'>Comments & Questions</h1>

  <p>Pleasee let us know any comments or questions you may have about our plan.</p>

  <div class='form-group'>
    <textarea  name='comments' type='' rows='10' class='form-control' id='' value = '{{ old('comments') }}'></textarea>
    <div>{{ $errors->first('comments') }}</div>
  </div>

  <h1 class='py-3'>Individual Health Insurance</h1>

  <p>If you do not want to join our plan and would like some assistance evaluating your options in the Individual Health Insurance market, please select 'Yes' below and we will help you with this process.</p>

  <div class='form-group'>
    <select  class='form-control' id='sel1' name='wants_ind_health_quote'>
      <option  value='Yes' >Yes</option>
      <option  value='No' >No</option>
    </select>
 <div>{{ $errors->first('wants_ind_health_quote') }}</div>
  </div>

  {{-- <h1 class='py-3'>Status</h1>

  <div class='form-group'>
    <select  class='form-control' id='sel1' name='survey_status'>
      <option  value='In Progress' >In Progress</option>
      <option  value='Complete' >Complete</option>
    </select>
 <div>{{ $errors->first('survey_status') }}</div>
  </div> --}}


  {{-- Submit Button --}}

  <div class="container">
    <div class="row">
   <div class="col text-right">
      <button type="submit" name="action" value="next_step" class="btn btn-info">Submit</button>
    </div>
 </div>
</div>

@ endsection

У меня есть следующее в моем контроллере:

public function store(Request $request)
{
    //
    $test = Auth::check();
    $userid = Auth::id();
    $user = User::find($userid);


    if ($test == false){
        return redirect('/login');
    }

     else {

            $data = request()->validate ([
                'survey_providers_list' => '',
                'wants_ind_health_quote' => '',
                'comments' => '',

            ]);

            $user->update($data);


            return redirect ('/my-employer-plan');

        }
}

Я использовал dd, чтобы убедиться, что переменная $ user работает правильно и переменная $ data извлекает данные. Оба работают правильно. Однако данные в моей таблице не обновляются. Все столбцы в таблице написаны правильно. Все, что я могу думать, это то, что я не могу использовать функцию обновления здесь по какой-то причине.

Вот дд ($ user):

App\User {#1368 ▼
  #guarded: []
  #fillable: array:3 [▶]
  #hidden: array:2 [▶]
  #casts: array:1 [▶]
  #connection: "mysql"
  #table: "users"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:13 [▼
    "id" => 1
    "name" => "Wruce Bayne"
    "email" => "bobby@test.com"
    "email_verified_at" => null
    "password" => "$2y$10$cFtf.wT3BE0qbQ68oza8fuKAOYGyTULz1bhzAoL1O3rfHLt3BTI6i"
    "active_plan_id" => null
    "remember_token" => null
    "created_at" => "2020-01-14 22:37:37"
    "updated_at" => "2020-01-14 22:37:37"
    "survey_providers_list" => null
    "wants_ind_health_quote" => null
    "comments" => null
    "survey_status" => null
  ]
  #original: array:13 [▶]
  #changes: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #visible: []
  #rememberTokenName: "remember_token"
}

Ответы [ 2 ]

0 голосов
/ 15 января 2020
// Post controller
 public function update(Request $request, Post $post)
    {
        if($post->user_id != Auth::id())
        {
            Toastr::error('You are not authorized this post!!!!','Error');
            return redirect()->back();
        }
        $this->validate($request,[
            'title' =>'required',
            // 'zip' => 'zip',
            'image' => 'image',
            'categories' => 'required',
            'tags' => 'required',
            'body' => 'required',
            'live_demo' =>'required'
        ]);


        $zipfile = $request->file('zip');
        $slug = str_slug($request->title);
        if (isset($zipfile))
        {
            $currentDate = Carbon::now()->toDateString();
            $zipname = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $zipfile->getClientOriginalExtension();
            if (!file_exists('storage/uploads/zip'))
            {
                mkdir('storage/uploads/zip',0777,true);
            }
            unlink('storage/uploads/zip/'.$post->zip);
            $zipfile->move('storage/uploads/zip',$zipname);
        }else{
            $zipname = $post->zip;
        }


        $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());
            $image_resize->resize(1600,1066);
            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            unlink('storage/uploads/post/'.$post->image);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = $post->image;
        }

        $post->user_id = Auth::id();
        $post->title = $request->title;
        $post->slug = str_slug($request->title);
        $post->image = $imagename;
        $post->zip = $zipname;
        $post->body = $request->body;
        $post->price = $request->price;
        $post->live_demo = $request->live_demo;
        if(isset($request->status))
        {
            $post->status =true;
        }else
        {
            $post->status = false;
        }
        $post->is_approved = false;
        $post->save();
        $post->categories()->sync($request->categories);
        $post->tags()->sync($request->tags);
        Toastr::success('Post Successfully Updated:)','Success');
        return redirect()->route('user.post.index');
    }

    }
// Route

Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
    Route::resource('post','PostController');
    });

// Blade file

@extends('layouts.backend.app')

@section('title')
{{__('Post')}}
@endsection



@push('css')
 <link href="{{asset('backend/plugins/bootstrap-select/css/bootstrap-select.css')}}" rel="stylesheet" />
@endpush
@section('content')
<div class="container-fluid">
           <div class="container-fluid">
            <div class="block-header"><a href="{{route('user.post.index')}}"></a></div>
            <!-- Basic Validation -->
            <form action="{{route('user.post.update',$post->id)}}"  method="POST" enctype="multipart/form-data">
                                @csrf
                                @METHOD('PUT')
            <div class="row clearfix">
                <div class="col-lg-8 col-md-12 col-sm-12 col-xs-12">
                    <div class="card">
                        <div class="header">
                            <h2>{{__('EDIT POST')}}</h2>
                        </div>
                        <div class="body">

                                <div class="form-group form-float">
                                    <div class="form-line">
                                        <input value="{{old('title')}}{{$post->title}}" type="text" class="form-control" name="title" required>
                                        <label class="form-label">{{__('Post Title')}}</label>
                                    </div>
                                </div>
                            <div class="form-group form-float">
                                <div class="form-line">
                                    <input value="{{old('price')}}{{$post->price}}" type="text" class="form-control" name="price">
                                    <label class="form-label">{{__('Price')}}</label>
                                </div>
                            </div>
                                <div class="form-group form-float">
                                    <div class="form-group">
                                        <img src="{{ asset('storage/uploads/post/'.$post->image) }}" width="40px"height="30px" alt=""/>
                                        <input  type="file" class="form-control" name="image" >
                                        <label class="form-label btn btn-primary">{{__(' Your Project ScreenShot')}}</label>
                                    </div>
                                </div>

                                    <div class="form-group">
                                        <input type="checkbox" id="status" class="filled-in" name="status" value="1" {{ $post->status ==  true? 'checked' : ''}}>
                                        <label for="status">{{__('Status')}}</label>
                                    </div>
                                    <div class="form-group form-float">
                                        <div class="form-line">
                                            <input value="{{old('live_demo')}} {{$post->live_demo}}" type="text" class="form-control" name="live_demo" required>
                                            <label class="form-label">{{__('Live Demo')}}</label>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <input  type="file" class="form-control" name="zip" >
                                        <label class="form-label btn btn-warning">{{__(' Your Project  Upload')}}</label>
                                    </div>


                        </div>
                    </div>
                </div>
                <div class="col-lg-4 col-md-12 col-sm-12 col-xs-12">
                    <div class="card ">
                        <div class="header bg-blue">
                            <h2 class="">{{__('Categrories & Tags')}}</h2>
                        </div>
                        <div class="body">

                                <div class="form-group form-float">
                                    <div class="form-line" {{$errors->has('categories') ? 'fucused error' : '' }}>
                                        <select name="categories[]" id="category" class="form-control show-tick" data-live-search="true" multiple>
                                            <label for="category">{{__('Category Name')}}</label>
                                            @foreach($categories as $category)
                                            <option
                                                @foreach($post->categories as $postCategory)
                                                {{ $postCategory->id  == $category->id? 'selected' : '' }}
                                                @endforeach
                                             value="{{$category->id}}">{{$category->name}}</option>
                                            @endforeach
                                        </select>

                                    </div>
                                </div>

                                <div class="form-group form-float">
                                    <div class="form-line" {{$errors->has('tags') ? 'fucused error' : '' }}>
                                        <select name="tags[]" id="tag" class="form-control show-tick" data-live-search="true" multiple>
                                            <label for="tag">{{__('Tag Name')}}</label>
                                            @foreach($tags as $tag)
                                            <option 
                                                @foreach($post->tags as $postTag)
                                                {{$postTag->id == $tag->id? 'selected' : ''}}
                                                @endforeach
                                             value="{{$tag->id}}">{{$tag->name}}</option>
                                            @endforeach
                                        </select>

                                    </div>
                                </div>

                                <a class="btn btn-danger" href="{{route('user.post.index')}}">{{__('BACK')}}</a>
                                <button class="btn btn-primary waves-effect" type="submit">{{__('SUBMIT')}}</button>

                        </div>
                    </div>
                </div>
            </div>
            <div class="row clearfix">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                    <div class="card">
                        <div class="header">
                            <h2>{{__('Documanation')}}</h2>
                        </div>
                        <div class="body">
                              <textarea id="tinymce" name="body">
                               {{old('body')}} {!! $post->body!!}
                            </textarea>
                        </div>
                    </div>
                </div>
            </div>
            </form>
        </div>
@endsection

@push('js')
<script src="{{asset('backend/plugins/bootstrap-select/js/bootstrap-select.js')}}"></script>
  <script src="{{ asset('backend/plugins/tinymce/tinymce.js') }}"></script>
    <script>
        $(function () {
            //TinyMCE
            tinymce.init({
                selector: "textarea#tinymce",
                theme: "modern",
                height: 300,
                plugins: [
                    'advlist autolink lists link image charmap print preview hr anchor pagebreak',
                    'searchreplace wordcount visualblocks visualchars code fullscreen',
                    'insertdatetime media nonbreaking save table contextmenu directionality',
                    'emoticons template paste textcolor colorpicker textpattern imagetools'
                ],
                toolbar1: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
                toolbar2: 'print preview media | forecolor backcolor emoticons',
                image_advtab: true
            });
            tinymce.suffix = ".min";
            tinyMCE.baseURL = '{{ asset('backend/plugins/tinymce') }}';
        });
    </script>
@endpush
0 голосов
/ 15 января 2020

сначала в модели пользователя, добавьте ниже код

protected $fillable = [
    'survey_providers_list' , 
    'wants_ind_health_quote' , 
    'wants_ind_health_quote'
];

opssss Редактировать код: вы заполнили модель пользователя результатом проверки !!!

       $validation = request()->validate ([
            'survey_providers_list' => '',
            'wants_ind_health_quote' => '',
            'comments' => '',
        ]);

        $user->update($request->all());
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...