Array to string conversion using laravel - 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
}

Related

I want to make validation for same user assigned using laravel

I am a beginner and I am trying to make validation for the user assigned when I assign the same user again when I submit so the error message should be shown, this user is already assigned please help me how to do this? thanks.
Controller
public function adduseraction(REQUEST $request) {
// Users_permissions::where('user_id',$request->userid)->get()-
// >pluck('user_Access_id');
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
html view
<form action="{{route('adduseraction')}}" method="post">
{{ csrf_field() }}
<div class="col-sm-4">
<label>Select User</label>
<select name="userid" class="form-control" id="typeofworkday">
<option>Select User</option>
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->name}}</option>
#endforeach
</select>
</div>
<br> <br> <br>
<div class="card-body">
<label>Select Muliple User or One</label>
<!-- Minimal style -->
<div class="row">
#foreach($users as $user)
<div class="col-sm-2">
<div class="form-check">
<input type="checkbox" id="check" 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>
<br><br><br><br>
<div class="card-footer">
<button type="submit" name="btnsubmit" class="btn btn-primary col-
md-2 center">Submit</button>
</div>
</form>
Ok you can do something like below
First check does user already exists in the table and if exists return redirect with the error message or else insert the data
public function adduseraction(Request $request) {
$isUserAvailable = Users_permissions::where('user_id',$request->userid)->get()- >pluck('user_Access_id');
//If user already exists
if($isUserAvailable) {
return redirect('admin')->with('error', 'Users has been assigned');
}else{
$useradd=$request->get('userid');
$checkid=$request->get('multiusersid');
$array = array();
foreach($checkid as $id){
$array[] = array('user_id'=>$useradd,'user_Access_id'=>$id);
}
$user=Users_permissions::insert($array);
return redirect('admin')->with('success', 'Users has been assigned');
}
}

Undefined variable: category in edit.blade

edit.blade.php
#extends('admin.layout')
#section('content')
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Добавить категорию
<small>приятные слова..</sma
ll>
</h1>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Меняем категорию</h3>
#include('admin.errors')
</div>
<div class="box-body">
{{Form::open(['route'=>['categories.update',$category->id], 'method'=>'put'])}}
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" id="exampleInputEmail1" name="title" placeholder="" value="{{$category->title}}">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-warning pull-right">Изменить</button>
</div>
<!-- /.box-footer-->
{{Form::close()}}
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
#endsection
<?php
namespace App\Http\Controllers\Admin;
use View;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
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('categories.index');
}
public function edit($id)
{
$category = Category::find($id);
return view('admin.categories.edit', ['category=>$category']);
}
public function update(Request $request, $id)
{
$category = Catefory::find($id);
$category->update($request->all());
return redirect()->route('categories.index');
}
}
CategoryController.php
ErrorException (E_ERROR)
Undefined variable: category (View: W:\domains\blog\resources\views\admin\categories\edit.blade.php)
Previous exceptions
I do not understand what the error checked everything a few times
['categories.update',$category->id], 'method'=>'put'])); ?>
<div class="col-md-6">
It happens because you've misplaced the ', you should pass the value correctly in return
replace your edit method with this:
public function edit($id)
{
$category = Category::find($id);
return view('admin.categories.edit', ['category' => $category]);
}
When posting code try to make it as readable as possible. Easiest way to accomplish that is to read the WHOLE post before you post it.
On the issue:
In the CategoriesController#edit reaplace
['category=>$category']
with
['category'=>$category]
Also in this scenario you can use the
compact('category')
instead of the array as the variable $category and the key in the array 'category' have same name.
it's simple as you know!
just replace in your edit function
return view('admin.categories.edit', ['category=>$category']);
with:
return view('admin.categories.edit')->withCategory($category);

How to fix this error in Laravel when creating a category

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() !!}

"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.

Resources