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

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.

Related

Laravel - How to update checkbox field value

Using Laravel-5.8, I have been able to save the data into the database including the check box field.
protected $fillable = [
'appraisal_name',
'is_current',
'appraisal_start',
'appraisal_end',
];
public function rules()
{
return [
'appraisal_name' => 'required|min:5|max:100',
'appraisal_start' => 'required',
'appraisal_end' => 'required|after_or_equal:appraisal_start',
'is_current' => 'nullable|boolean',
];
}
public function create()
{
return view('appraisal.appraisal_identities.create');
}
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
public function edit($id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$identity = AppraisalIdentity::where('id', $id)->first();
return view('appraisal.appraisal_identities.edit')->with('identity', $identity);
}
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
create.blade
<form action="{{route('appraisal.appraisal_identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
edit.blade
<form action="{{route('appraisal.appraisal_identities.update', ['id'=>$identity->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group row">
<label class="control-label text-right col-md-3">Is Current Appraisal?</label>
<div class="col-md-9">
<input type="checkbox" class="form-control" name="is_current" value="{{old('is_current')}}">
</div>
</div>
</div>
</div>
</div>
<div>
<!--<input class="btn btn-primary" type="submit" value="{{ trans('global.save') }}">-->
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('appraisal.appraisal_identities.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
I have these issues while trying to update the data?
The edit checkbox field (is_current) did not pick the value from the database when loaded. It remains unchecked.
is_current is either 0 or 1. The goal is that, there can only be one is_current field that is set to 1 in the table. From the checkbox, when is_current is checked to 1, it should set any other is_current that is 1 to 0 in the table.
How do I resolve these issues?
Thank you.
In edit blade update your checkbox code as this:
<input type="checkbox" class="form-control" name="is_current" #if($identity->is_current == 1) checked #endif value="{{old('is_current')}}">
In your update function change this:
public function update(UpdateAppraisalIdentityRequest $request, $id)
{
abort_unless(\Gate::allows('appraisal_identity_edit'), 403);
$appraisalStart = Carbon::parse($request->appraisal_start);
$appraisalEnd = Carbon::parse($request->appraisal_end);
$submissionStart = Carbon::parse($request->submission_start);
$submissionEnd = Carbon::parse($request->submission_end);
$identity = AppraisalIdentity::find($id);
$identity->appraisal_name = $request->appraisal_name;
$identity->appraisal_start = $appraisalStart;
$identity->appraisal_end = $appraisalEnd;
$identity->is_current = $request->has('is_current');
$identity->save();
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is updated successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
In your store function change this:
public function store(StoreAppraisalIdentityRequest $request)
{
$identity = AppraisalIdentity::create([
'appraisal_name' => $request->appraisal_name,
'appraisal_start' => $appraisalStart,
'appraisal_end' => $appraisalEnd,
'is_current' => $request->has('is_current'),
]);
$id = $identity->id;
// this line update all column to 0 and leave $id field
AppraisalIdentity::where('id', '!=', $id)->update(['is_current' => 0]);
Session::flash('success', 'Appraisal Initialization is created successfully');
return redirect()->route('appraisal.appraisal_identities.index');
}
try this in the edit blade
<
is_current == 1 ? checked : value="{{old('is_current')}}">

Edit two unique value with laravel

I have a problem with my Laravel 5.8 project. I want to edit one of two field that both have unique value.
Blade:
#extends('layouts.master')
#section('content')
<h1>CHANGE SURGICAL DIVISION</h1>
<a href="/surgical-div">
<button type="button" class="btn btn-primary btn-sm">BACK</button><br>
</a>
#if (session('mess'))
<div class="alert alert-success">
{{ session('mess')}}
</div>
#endif
<form method="POST" action="/surgical-div/{{ $surgicaldivs->id_surgical_div }}">
#method('patch')
#csrf
<div class="form-group">
<label for="name_surgical_div">Surgical Division Name: </label>
<input type="text" value="{{ $surgicaldivs->name_surgical_div }}"
class="form-control #error('name_surgical_div') is-invalid #enderror" id="name_surgical_div" name="name_surgical_div"
placeholder="Insert The Surgical Division">
#error('name_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group">
<label for="initial_surgical_div">Surgical Division Initial : </label>
<input type="text" value="{{ $surgicaldivs->initial_surgical_div }}"
class="form-control #error('initial_surgical_div') is-invalid #enderror" id="initial_surgical_div" name="initial_surgical_div"
placeholder="Insert Surgical Division Initial">
#error('initial_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-success btn-sm">Save</button>
</form>
#endsection
Controller:
public function edit($id)
{
$surgicaldivs = SurgicalDiv::withTrashed()->find($id);
return view('pages.surgical_div.surgical_div_edit', compact('surgicaldivs'));
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SurgicalDiv extends Model
{
//Table Name
protected $table = 'surgical_div';
// Primary Key
protected $primaryKey = 'id_surgical_div';
//Soft Deletes
use SoftDeletes;
//Fillable Field
protected $fillable = ['name_surgical_div', 'initial_surgical_div'];
}
This is the update in the controller that i've tried :
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div',
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div'
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
I don't know what to put on the update function in the controller. I want to update one or even both of the field from my blade.
Try this
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div,'.$id,
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div,'.$id
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
This will check the table for same entries except the row with the $id. This way you can check if there are any other rows with same values in the two columns.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pk5.roles' doesn't exist

I am able to insert records to employee_roles through tinker but unable to insert them through code
Role.php
<?php
namespace App\Models\Admin\Employee;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = 'employee_roles';
public function permissions()
{
return $this->belongsToMany('App\Models\Admin\Employee\Permission', 'employee_permission_role', 'role_id', 'permission_id');
}
}
RoleController.php
<?php
namespace App\Http\Controllers\Admin\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Employee\Employee;
use App\Models\Admin\Employee\Role;
use App\Models\Admin\Employee\Permission;
class RoleController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function index()
{
$roles = Role::all();
return view('admins.employees.roles.role', compact('roles'));
}
public function create()
{
$permissions = Permission::all();
return view('admins.employees.roles.create',compact('permissions'));
}
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'name' => 'required|unique:roles'
]);
$role = new Role();
$role->name = $request['name'];
$role->save();
$role->permissions()->sync($request->permission);
return redirect(route('admin.employee.role.index'));
}
admins.employees.roles.create.blade.php
#extends('layouts.admin')
#section('title', 'Role - Create')
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Add an Employee Role</h1>
<br><br>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('admin.employee.role.store') }}" method="post">
#csrf
<div class="form-group">
<label for="name">Role Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Role Name" value="{{ old('name') }}">
</div>
<div class="form-row">
<div class="col-md-4">
<label for="name"><b>Customer Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Customer')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
<div class="col-md-4">
<label for="name"><b>Despatch Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Despatch')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
Back
</div>
</form>
#endsection
#section('pagescript')
#stop
$this->validate($request, [
'name' => 'required|unique:roles'
]);
You should fix table name as employee_roles
Because you don't have table as roles you said that in your Role model you're using employee_roles table ( protected $table = 'employee_roles';)

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.

Eloquent create not working in 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

Resources