How to fix this error in Laravel when creating a category - laravel

I am creating a website for a blog. I have added a category page quickly updated, but not returned to the index: category.php,CategoriesController.php. I'm using Laravel v5.5 and OpenServer.
Category.php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['title', 'slug',];
public function user()
{
return $this->belongsToMany(
User::class,
'id_idcat',
'gid',
'idcat'
);
}
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
CategoriesController.php
namespace App\Http\Controllers\Admin;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use View;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('admin.categories.index', ['categories' => $categories]);
}
public function create()
{
return view('admin.categories.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required' //обязательно
]);
Category::create($request->all());
return redirect()->route('admin.categories.index');
}
}
create.blade.php
{!! Form::open(['route' => 'categories.store']) !!}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" name="cat">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}
I can not find a mistake. I did similar tasks several times.

Your Data isn't validating as there is no input named title because it's named cat, so your validator is redirecting you back with errors, but your blade isn't showing errors so you don't see them.
Change Name of the field in your create view and add errors as below:
Edit: also add CSRF to form
create.blade.php
#if ($errors->any())
<div class="alert alert-danger" role="alert">
#foreach ($errors->all() as $input_error)
{{ $input_error }}
#endforeach
</div>
#endif
{!! Form::open(['route' => 'categories.store']) !!}
{{ csrf_field() }}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" placeholder="" name="title">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}

Related

multiple field validation using livewire ? name.0.required is working but name.*.required is not working. Please provide me solution

I want to validate all field. But It is validating only first field. Append field is not validating
multiple fields validation using livewire? name.0.required is working but name.*.required is not working.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Test extends Component
{
public $name;
public $inputs = [];
public $i = 1;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->inputs ,$i);
}
public function remove($i)
{
unset($this->inputs[$i]);
}
public function store()
{
$validatedDate = $this->validate([
'name.0' => 'required',
'name.*' => 'required',
],
[
'name.0.required' => 'name field is required',
'name.*.required' => 'name field is required',
]
);
session()->flash('message', 'Name Has Been Created Successfully.');
}
public function render()
{
return view('livewire.test');
}
}
<div>
<form class="offset-md-3">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
#error('name.0') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
</div>
</div>
</div>
#foreach($inputs as $key => $value)
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
#error('name.'.$value) <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove</button>
</div>
</div>
</div>
#endforeach
<div class="row">
<div class="col-md-12">
<button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Save</button>
</div>
</div>
</form>
</div>
This is my full code use to create multi field using livewire. I am not able to validate appended field so I need help to solve this problem. This validate first field name.0 other append field name.* does not validate.
You should use $key instead $value.
Like this:
wire:model="name.{{ $key }}"

Array to string conversion using laravel

I am trying to send a multi user-id into the database when I select users from the checkbox then I click to submit so I face error Array to string conversion how can I resolve this issue? please help me thanks.
please see error
https://flareapp.io/share/17DKWRPv
controller
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
$user->save();
}
html view
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Users Permission </h3>
</div>
<br>
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<select name="userid" class="form-control">
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<div class="card-body">
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" name="multiusersid[]" value="{{$user->id}}" class="form-check-input" >
<h5 style="position:relative;left:10px;">{{$user->name}}</h5>
</div>
<!-- checkbox -->
</div>
#endforeach
</div>
<!-- /.card-body -->
</div>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-md-2
center">Submit</button>
</div>
</form>
</div>
<!-- /.content-wrapper -->
Route
Route::post('adduseraction','AdminController#adduseraction')->name('adduseraction');
** current status **
{"_token":"4Z3ISznqKFXTMcpBKK5tUgemteqxuJjQpKF8F0Ma","userid":"6","multiusersid":["2","5","7"],"btnsubmit":null}
use implode($checkid, ',');
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> implode($checkid, ',');
]);
}
Change in your Users_permissions model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users_permissions extends Model
{
protected $table = 'userspermissions';
protected $fillable = [
'user_id','user_Access_id'
];
}
Here is your solution
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=implode(",", $request->get('multiusersid'));
Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> $checkid
]);
}
It is expecting a string and you are passing an array of ids. You may want to change the database to json or do json_ecode(checkid). Which will stringify your array. then you can store. However, remember you will need to convert it back with typecasting or manually doing it.
example:
public function adduseraction(REQUEST $request)
{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$user=Users_permissions::create([
'user_id'=>$useradd,
'user_Access_id'=> json_encode($checkid)
]);
// $user->save(); // yes obviously not needed
}

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

Cant Display my Reply under the Comment Laravel 5.7

I can't display my reply under each comment. Here is my code...
Comment model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id', 'topic', 'body', 'category',
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
Comment controller
<?php
namespace App\Http\Controllers;
use App\Comment;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CommentController extends Controller
{
public function store(Request $request, $post)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$post = Post::find($post);
$post->comments()->save($comment);
return back();
}
public function replyStore(Request $request, $comment)
{
$comment = new Comment;
$comment->body = $request->body;
$comment->user_id = Auth::user()->id;
$comment = Comment::find($comment);
$comment->comments()->save($comment);
return back();
}
}
Routes
Route::post('/comment/store/{post}', 'CommentController#store')->name('comment.add');
Route::post('/reply/store/{commentid}', 'CommentController#replyStore')->name('reply.add');
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="card">
<div class="card-header">{{$post->topic}}
Create New Post
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<h3>{{$post->topic}}</h3>
<p>{{$post->body}}</p>
</div>
</div>
<form action="/comment/store/{{$post->id}}" method="post" class="mt-3">
#csrf
<div class="form-group">
<label for="">Comment :</label>
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Comment" class="btn btn-secondary">
</div>
</form>
<div class="row mt-5">
<div class="col-md-10 mx-auto">
<h6 style="border-bottom:1px solid #ccc;">Recent Comments</h6>
#foreach($post->comments as $comment)
<div class="col-md-12 bg-white shadow mt-3" style="padding:10px; border-radius:5px;">
<h4>{{$comment->user->name}}</h4>
<p>{{$comment->body}}</p>
<button type="submit" class="btn btn-link" onclick="toggleReply({{$comment->id}})">
Reply
</button>
<div class="row">
<div class="col-md-11 ml-auto">
{{-- #forelse ($replies as $repl)
<p>{{$repl->body}}</p>
#empty
#endforelse --}}
</div>
</div>
</div>
<form action="/reply/store/{{$comment->id}}" method="post"
class="mt-3 reply-form-{{$comment->id}} reply d-none">
#csrf
<div class="form-group">
<textarea class="form-control" name="body" id="" rows="3"></textarea>
<br>
<input type="submit" value="Reply" class="btn btn-secondary">
</div>
</form>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
#section('js')
<script>
function toggleReply(commentId) {
$('.reply-form-' + commentId).toggleClass('d-none');
}
</script>
#endsection
I have created the normal table with parent_id but I don't know how to display the replies for each comment. Please, anyone who can help me with this - I am stranded here and the error coming from the second controller function which is replystore() saying it doesn't recognize the comments() method. Please help me out to display the reply.

Undefined variable: section (View: D:\xampp\htdocs\laravel5\resources\views\cms\sections.blade.php)

I try to made simple crud and found this error
Undefined variable: section
(View:D:\xampp\htdocs\laravel5\resources\views\cms\sections.blade.php)
Route:
Route::resource('sections','SectionsController');
View:
{!! Form::open(["url"=>"sections","files" => "true"]) !!}
section name: {!! Form::text("section_name")!!}
<hr/>
{!! Form::file('image',["class"=>"filestyle","data-buttonText"=>"select image","data-input"=>"false"]) !!}
<br/>
{!! Form::submit("insert#upload",["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
<div class="row">
<h3>get data from db ::</h3>
#foreach($sections as $section)
<div class="col-md-3">
<div class="thumbnail">
<p>{{$section->section_name}}</p>
<img src="/uploads/{{$section->image_name}}" width="90%" height="90%">
</div>
</div>
#endforeach
</div>
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "patch"]) !!}
{!! Form::text("section_name",$section->section_name)!!}
{!! Form::submit("update",["class"=>"btn btn-success"]) !!}
{!! Form::close() !!}
</div>
</div>
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "delete"]) !!}
{!! Form::submit("delete",["class"=>"btn btn-danger"]) !!}
{!! Form::close() !!}
</div>
</div>
</div>
Controller:
use DB;
use Input;
use Validator;
class SectionsController extends Controller {
public function index() {
$section=DB::table('sections')->get();
return view('cms.sections')->withSections($section);
}
public function create() {
return view('cms.sections');
}
public function store(Request $request) {
$this->validate($request,
['section_name' => 'required|unique:sections,section_name|max:20',
'image' => 'mimes:jpeg|max:1024']);
$section_name=$request->input('section_name');
$file=$request->file('image');
$destinationPath='uploads';
$filename=$file->getClientOriginalName();
$file->move($destinationPath,$filename);
$rules = array('image' => 'mimes:jpg,png,gif|required|max:10000');
$validator = Validator::make(Input::all(), $rules);
DB::table('sections')->insert(['section_name' => $section_name,
'image_name' => $filename]);
return redirect('sections');
}
public function update(Request $request, $id) {
$section_name=$request->input('section_name');
DB::table('sections')->where('id',$id)->update(['section_name'=>$section_name]);
return redirect('sections');
}
public function destroy($id) {
DB::table('sections')->where('id',$id)->delete();
return redirect('sections');
}
}
There is one definite problem in your View code: You use $section after you end your #foreach block that defines it, for example here:
#foreach($sections as $section)
...
#endforeach
...
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "patch"]) !!}
------------------------------------^^^^^^^^
I suspect you intended to place the <div class="row"> blocks inside your #foreach block.

Resources