SQLSTATE [42S22]: Столбец не найден: 1054 Неизвестный столбец «заголовок» в «предложении где» (SQL: выбор количества (*) - PullRequest
0 голосов
/ 27 августа 2018

Я создаю новостной портал для администратора.Я хочу создать раздел менеджера категорий. Я создал менеджер категорий, но пока я отправляю форму, я получаю следующие ошибки:

SQLSTATE [42S22]: столбец не найден: 1054 Заголовок неизвестного столбца'в' предложении где '(SQL: выберите количество (*) в качестве агрегата из categories, где title = Непал)

таблица миграции для категории:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryTable extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();

            $table->string('title',255);
            $table->string('slug',100)->unique();
            $table->text('image')->nullable();
            $table->boolean('status')->default(0);
        });
    }


    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

У меня естьсоздал модель следующим образом: Models Category.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';
    protected $fillable = ['title', 'slug', 'image', 'status'];

}

views: form.blade.php

<div class="form-group">

    {!! Form::label('title', 'Title', ['class' => 'col-sm-3 control-label no-padding-right']) !!}


    <div class="col-sm-9">
        {!! Form::text('title', null, [
        'id' => 'title',
        'placeholder' => 'Title',
        'class' => 'col-xs-10 col-sm-5'
          ]) !!}

        @if($errors->has('title'))
            <span class="help-block error">
            <strong>{{ $errors->first('title') }}</strong>
            </span>
            @endif
    </div>
</div>

@if(isset($data['row']))

    <div class="form-group">

        {!! Form::label('existing_image', 'Existing Image', ['class' => 'col-sm-3 control-label no-padding-right']) !!}


        <div class="col-sm-9">
            @if($data['row']->image)
                <img src="{{ asset('images/.$folder.'.$data['row']->image) }}" alt="" width="140">
              @else
                <p>No image</p>
            @endif
        </div>
    </div>
    @endif
<div class="form-group">
    {!! Form::label('image', 'Image', ['class' => 'col-sm-3 control-label no-padding-right']) !!}

    <div class="col-sm-9">
        {!! Form::file('image', [
        'id' => 'image',
        'class' => 'col-xs-10 col-sm-5'
        ]) !!}

        @if($errors->has('image'))
            <span class="help-block error">
            <strong>{{ $errors->first('image') }}</strong>
            </span>
        @endif
    </div>
</div>
<div class="form-group">
    {!! Form::label('status', 'Status', ['class' => 'col-sm-3 control-label no-padding-right' ]) !!}

    <div class="col-sm-9">
        <div class="control-group">
            <div class="radio">

                <label>
                    {!! Form::radio('status', 'active', true, ['class' => 'ace']) !!}
                    <span class="lbl">Active</span>
                </label>
            </div>
            <div class="radio">
                <label>
                    {!! Form::radio('status', 'in-active', false, ['class' => 'ace']) !!}
                    <span class="lbl">Inactive</span>
                </label>
            </div>
        </div>
    </div>
</div>

controller: CategoryController.php

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Requests\Category\AddFormValidation;
use App\Http\Requests\Category\EditFormValidation;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends AdminBaseController
{
    protected $base_route = 'admin.category';
    protected $view_path = 'admin.category';
    protected $folder_name = 'category';
    protected $panel = 'Category';
    protected $folder_path;

    public function __construct()
    {
       $this->folder_path = public_path().DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.$this->folder_name;
    }

    public function index()
    {

        $data = [];
        $data['rows'] = Category::select('id', 'created_at', 'title','image','status')->get();


        return view(parent::loadDataToView($this->view_path.'.index'),compact('data'));
      }

    public function add()
    {
        return view(parent::loadDataToView($this->view_path.'.add'));
    }

    public function store(AddFormValidation $request)
    {

          if($request->hasFile('main_image')){
              $image = $request -> file('main_image');
              $image_name = rand(1000, 5000).'_'.$image->getClientOriginalName();
              $image->move($this->folder_path, $image_name);
          }

        $request->request->add([
            'slug' => str_slug($request->get('title')),
            'status' => $request->get('status') == 'active'?1:0,
            'image' => $image_name
        ]);

        Category::create($request->all());
        $request->session()->flash('success_message','Category added successfully');
        return redirect()->route($this->base_route);
    }

    public function edit(Request $request, $id){
              $data = [];
              $data['row'] = Category::where('id', $id)->first();

        if(!$data['row']){
            $request->session()->flash('error_message','Invalid request.');
            return redirect()->route($this->base_route);
        }
        $data['row']->status = $data['row']->status == 1?'active':'in-active';
        return view(parent::loadDataToView($this->view_path.'.edit'),compact('data'));

    }

    public function update(EditFormValidation $request, $id)
    {
        $data=[];
        $data['row'] = Category::where('id',$id)->first();

        if($request->hasFile('main_image')){

            $image = $request -> file('main_image');
            $image_name = rand(1000, 5000).'_'.$image->getClientOriginalName();
            $image->move($this->folder_path, $image_name);

            if( $data['row']->image && file_exists($this->folder_path.DIRECTORY_SEPARATOR.$data['row']->image))
            unlink($this->folder_path.DIRECTORY_SEPARATOR.$data['row']->image);
        }

            $request->request->add([
                'slug' => str_slug($request->get('title')),
                'status' => $request->get('status') == 'active'?1:0,
                'image' => isset($image_name)?$image_name:$data['row']->image
            ]);
        $data['row']->update($request->all());
        $request->session()->flash('success_message','Category added successfully');
        return redirect()->route($this->base_route);
    }

    public function delete(Request $request, $id)
    {
        $data = [];
        $data['row'] = Category::where('id', $id)->first();

        if(!data['row']){
            $request->session()->flash('error_message','Invalid request.');
            return redirect()->route($this->base_route);
        }


        if( $data['row']->image && file_exists($this->folder_path.DIRECTORY_SEPARATOR.$data['row']->image))
            unlink($this->folder_path.DIRECTORY_SEPARATOR.$data['row']->image);

        $data['row']->delete();
        $request->session()->flash('success_message','Category deleted successfully');
        return redirect()->route($this->base_route);
    }

}

AdminBaseController.php

<?php
namespace App\Http\Controllers\Admin;
use View;
use App\Http\Controllers\Controller;
class AdminBaseController extends Controller
{
    protected function loadDataToView($view_path)
    {
        View::composer($view_path, function($view){
           $view->with('base_route',$this->base_route);
           $view->with('panel',$this->panel);
            $view->with('folder',property_exists($this,'folder_name')?$this->folder_name:'');
        });
        return $view_path;
   }

}

AddFormValidation.php

<?php

namespace App\Http\Requests\Category;

use Illuminate\Foundation\Http\FormRequest;

class AddFormValidation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required | unique:categories, title',
            'image' => 'required | mimes:jpeg,bmp,png ',
        ];
    }
}

EditFormValidation.php

<?php

namespace App\Http\Requests\Category;

use Illuminate\Foundation\Http\FormRequest;

class EditFormValidation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required | unique:categories,'.$this->request->get('id'),
            'main_image' => 'mimes:jpeg,bmp,png '
        ];
    }

}

таблица базы данных введите описание изображения здесь

скриншот ошибки: введите описание изображения здесь

1 Ответ

0 голосов
/ 27 августа 2018

Вы должны удалить пробел из (title) в вашем AddFormValidation.php здесь:

'title' => 'required | unique:categories, title',

И попробуйте с:

'title' => 'required|unique:categories,title',

Beacuase это имя столбца.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...