Eloquent create not working in laravel - laravel

I am new to laravel, so I face a problem in creating a post.
Here is my route:
Route::post('savepost', 'PostsController#savepost');
Here are my createpost.blade.php
#include('header')
<div class="container">
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h3>Create New Post</h3>
<form action="savepost" class="form-horizontal" method="post" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 control-label">Post Title</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="title" id="inputEmail3" placeholder="Enter New Title">
</div>
#if($errors->has('title'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('title') }} </p>
#endif
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-4 control-label">Post Description</label>
<div class="col-sm-8">
<textarea name="description"></textarea>
</div>
#if($errors->has('description'))
<p class="alert alert-danger"><strong>oopps! </strong>{{ $errors->first('description') }} </p>
#endif
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" class="btn btn-default" value="Save Post">
</div>
</div>
</form>
</div>
</div> <!-- /container -->
#include('footer')
Here are my PostsController
class PostsController extends BaseController{
public function createpost(){
return View::make('createpost');
}
public function savepost(){
$input = Input::all();
$validation = Validator::make($input, Posts::$rules);
if ($validation->passes())
{
Posts::create(array(
'title'=>Input::get('title'),
'description'=>Input::get('description')
));
}
else{
return Redirect::route('createpost')->withErrors($validation);
}
}
}
Here are my Model:
class Posts extends Eloquent {
protected $guarded = array();
protected $fillable = array('name', 'description');
protected $table = 'posts';
public static $rules = array(
'title' => 'required|min:5',
'description' => 'required'
);
}
and here are my posts database
id title description url date
please help me

Your posts table is missing the default laravel timestamps. Either turn them off in your model by doing:
public $timestamps = false;
Or add them to your posts table:
alter table posts add created_at datetime NOT NULL
alter table posts add updated_at datetime
Or create your own timestamps in your model. I see you have a date column, so you can do something like:
const CREATED_AT = 'date';

You can't use both fillable and guarded.
Of course, you should use either $fillable or $guarded - not both.
https://laravel.com/docs/5.3/eloquent#mass-assignment

Related

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.

laravel-5.7: data is not saving into db

hi m trying to save data into db but it return only the next page without saving data into db, is there any solution to fix this problem,
controller:
public function create(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
$categories = new Categories;
$categories->name = $data['category_name'];
$categories_description = $data['description'];
$categories->save();
return view('admin.categories.index');
}
return view('admin.categories.create');
}
blade file:
<form class="k-form" method="post" action="{{ url('/admin/categories/index')}}" name="" id="k_form">#csrf
<div class="row">
<label class="col-3 col-form-label">Category Name:</label>
<div class="col-9">
<input class="form-control" type="text" name="category_name" value="" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Description:</label>
<div class="col-9">
<textarea name="description" required="required"></textarea>
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label"></label>
<div class="col-9">
<div class="k-checkbox-single">
<input type="submit" value="Add Category" style="background-color: #5867dd; color: #fff; border-radius: 5px; padding: 10px;" name="">
</div>
</form>
route:
Route::match(['get', 'post'],'/admin/categories/create','CategoriesController#create');
You mistaken here
$categories_description = $data['description'];
It should be
$categories->description = $data['description'];
Hope this helps :)
Problem is in
$categories = new Categories;
I believe it should be
$categories = new Category;
or
$category = new Category; //preferred
Model is singular where as table is plural as per laravel naming convention.
Further, add column names to fillable array if you are mass assigning the values. Like
protected $fillable = ['name', 'description'];
Also, make sure your model is in App folder and you have not created any sub directories such as 'App\Models' or something.

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

Updating Item from Pivot Table Fields

I have item_color and item_size pivot tables, and would like to update my size and color fields using their field values, and an not exactly sure where to start. Here's what I have so far.
ItemSize.php
<?php
class ItemSize extends \Eloquent
{
protected $table = 'item_size';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
ItemColor.php
<?php
class ItemColor extends \Eloquent
{
protected $table = 'item_color';
protected $fillable = [];
public function item() {
return $this->belongsTo('Item');
}
}
VendorController
public function postVendorUpdateItems ($id)
{
$input = Input::all();
$items = Item::find($id);
$validator = Validator::make($input,
[ 'item_name' => 'max:50',
'item_id' => 'max:50',
'normalprice' => 'numeric',
'karmaprice' => 'numeric',
'asin' => 'max:50',
]);
if($validator->passes())
{
$items->name = $input['item_name'];
$items->normalprice = $input['normalprice'];
$items->karmaprice = $input['karmaprice'];
$items->asin = $input['asin'];
$items->id = $input['item_id'];
$items->save();
return Redirect::route('account-vendor-index')
->with('global', 'You have updated your item.');
}
return Redirect::route('account-vendor-index')
->withErrors($validator)
->with('global', 'Your item could not be updated.');
}
View
<form class="form-horizontal" role="form" method="post" action="{{url('account/vendor/update/items')}}/{{$item->id}}">
<input type="hidden" id="brand_id" placeholder="brand_id" value="{{$brand->id}}" name="brand_id">
<input type="hidden" id="item_id" placeholder="item_id" value="{{$item->id}}" name="item_id">
<div class="form-group">
<label for="colors" class="col-xs-3 control-label">Colors</label>
<div class="col-xs-6">
<input type="text" class="form-control input-sm" id="colors" name="colors" placeholder="#foreach($item->colors as $color){{$color->color}}#endforeach" value="">
</div>
<button type="" class="btn btn-primary btn-sm">Add color</button>
<div class="clear"></div>
<div class="col-xs-offset-3 showColors">
#foreach($item->colors as $color)
{{$color->color}}
#endforeach
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Sizes</label>
<div class="col-xs-9">
<select id="selectSizes" multiple="multiple" class="form-control selectSizes" name="sizes">
<option value="XS (0-2)">XS (0-2)</option>
<option value="S (4-6)">S (4-6)</option>
<option value="M (8-10)">M (8-10)</option>
<option value="L (12-14)">L (12-14)</option>
<option value="XL (16-18)">XL (16-18)</option>
<option value="XXL (20-22)">XXL (20-22)</option>
</select>
</div>
</div>
<div class="form-group bot-0">
<div class="col-xs-offset-3 col-xs-9">
<button type="submit" class="btn btn-main btn-sm">Save changes</button>
</div>
</div>
</form>
item_size and item_color are not pivot tables. They are in fact a one to one relationship with your schema. If want you truly want are pivot tables, you need to define a color and a size table, then create a many-to-many relationship. See here: https://laravel.com/docs/master/eloquent-relationships
Then to update related models, you'll use the attach, sync, detach, etc. methods.
Also, what version of Laravel are you running? If you're running 5.1+ look into form request validation. See here: https://laravel.com/docs/master/validation#form-request-validation
That will remove all the validation logic from your controller.

Resources