Display name of select form rather than it's Id (error:Trying to get property of non-object) laravel 5 - php

I have 2 tables tn_client and tn_project, which project have 1 client while client can have many projects, rather than displaying client id on my table, i want display its client name but when i did that its said trying to get property of non-object.
Trying to get property of non-object (View:
C:\xampp\htdocs\PKL\netxcel-activityreport-11b90b878d39\resources\views\project.blade.php)
Above is the full error that i get, and below is the tables
tn_project
tn_client
CONTROLLER
public function index(){
Log::info('Entering index');
return view('project')
->with('title','Project')
->with('projects',Project::with('client','invoice')->get())
->with('clients',Client::all())
->with('invoices', Invoice::all());
}
//get all data
public function getAll(){
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
public function createOrEdit(){
$currentUsername = Auth::user()->name;
$isUpdate = false;
$projectId = Input::get('prevId');
//populate data
$project = new Project;
if($projectId != ""){
$project = Project::where('cv_id','=',$projectId)->firstOrFail();
$project->cv_updated_by = $currentUsername;
$project->cn_updated_at = Carbon::now();
$isUpdate = true;
} else{
$project->cv_created_by = $currentUsername;
$project->cn_created_at = Carbon::now();
}
$project->cv_id = Input::get('projectId');
$project->cv_name = Input::get('projectName');
$project->cv_client_id = Input::get('clientId');
$project->cn_invoice_method = Input::get('invoiceId');
$project->cn_project_rate = Input::get('projectRate');
$project->cn_note = Input::get('note');
//execute
if($isUpdate){
Log::info("entering update mode");
Project::where('cv_id','=',$projectId)->update(['cv_id'=>$project->cv_id,
'cv_name'=>$project->cv_name,
'cv_client_id'=>$project->cv_client_id,
'cn_invoice_method'=>$project->cn_invoice_method,
'cn_project_rate'=>$project->cn_project_rate,
'cn_note'=>$project->cn_note,
'cn_updated_at'=>$project->cn_updated_at,
'cv_updated_by'=>$project->cv_updated_by]);
}else{
$project->save();
}
return Response::json(
array(
'content' => Project::with('client','invoice')->get(),
'status' => 'success',
)
);
}
Model
PROJECT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Project extends Model {
protected $table = 'tn_project';
public $timestamps = false;
protected $fillable = [
'cv_id',
'cv_name',
'cv_client_id',
'cn_invoice_method',
'cn_project_rate',
'cn_note',
'cn_created_at',
'cv_created_by',
'cn_updated_at',
'cv_updated_by'
];
public function client(){
return $this->belongsTo('Activity\Client','cv_client_id','cn_id');
}
public function invoice(){
return $this->hasOne('Activity\Invoice','cn_id','cn_invoice_method');
}
}
CLIENT
<?php
namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Client extends Model {
protected $table = 'tn_client';
public $timestamps = false;
protected $fillable = [
'cv_name',
'cv_contact',
'cv_email',
'cv_phone',
'cv_address',
'cn_created_at',
'cn_created_by',
'cn_updated_at',
'cn_updated_by'
];
public function project(){
return $this->hasOne('Activity\Project', 'cv_id', 'cn_id');
}
}
VIEW
this is my select form
<div class="col-md-9">
<select name="clientId" id="clientId" class="form-control" placeholder="Select Client">
#foreach ($clients as $client)
<option value='{{$client->cn_id}}'>{{$client->cv_name}}</option>;
#endforeach
</select>
</div>
This is how i called the function to display it in my view
#foreach($projects as $project)
<tr class="odd gradeX">
<td>{{$project->cv_id}}</td>
<td>{{$project->cv_name}}</td>
<td>{{$project->client->cv_name}}</td><!--This is what cause an -->
<td>{{$project->cn_invoice_method}}</td>
<td>{{$project->cn_project_rate}}</td>
<td>{{$project->cn_note}}</td>
<td>
<a class="btn btn-success" title="edit" data-id={{$project->cv_id}} data-action="project-edit"><i class="fa fa-pencil"></i></a>
<a class="btn btn-danger" title="delete" data-id={{$project->cv_id}} data-action="project-delete"><i class="fa fa-times"></i></a>
</td>
</tr>
#endforeach
im still new to laravel, and what did i do wrong that make such an error like that?

I found the answer, i got the reference from here so based on that reference and the basic of x->y->z, we got to check first that x->y have some value in it if yes we got to check whether it's an object or just an array, in my case it was an array so rather doing something like this
{{$project->client->cv_name}}
which is that how to display an object, we should do something like this
{{$project->client['cv_name']}}
and that is how you solve your problem, cheers :D

Related

How Can I Query Polymorphic Relationship in Laravel 8

I am able to create and even delete a polymorphic row from my app, but I can not for the life of me able to figure out how to query the relationship so I can update the row. My models and controller methods are below--all work except for public function updateManifest($id). I didn't include all the update code I've been trying over the past day and a half because it would be too much and not really relevant, but I can tell you that I can only get as deep as the Workorder model, I can't seem to query anything related through the poly relationship so I can query all the manifest objects. Thank you.
Workorder.php
class Workorder extends Model
{
...
public function manifest(){
return $this->morphMany(Manifest::class, 'manifestable');
}
}
Manifest.php
class Manifest extends Model
{
use SoftDeletes;
protected $fillable = [
'stream_id', 'manifest_number', 'manifest_quantity', 'manifest_rate',
'manifest_total', 'manifestable_id', 'manifestable_type', 'stream_description_plus'
];
public function manifestable(){
return $this->morphTo();
}
}
edit.php (Workorder controller)
class Edit extends Component {
public function mount(Workorder $workorder, Manifest $manifest)
{
$this->workorder = $workorder;
$this->manifest = $manifest->manifestable;
$this->workorder_number = $workorder->workorder_number;
$this->workorder_po_number = $workorder->workorder_po_number;
$this->workorder_status = $workorder->workorder_status;
$this->workorder_job_notes = $workorder->workorder_job_notes;
$this->project_id = $workorder->project_id;
$this->customer_id = $workorder->customer_id;
$this->generator_id = $workorder->generator_id;
$this->prevailing_wage = $workorder->prevailing_wage;
$this->touched = false;
}
public function addManifest($id)
{
Manifest::create([
'workorder_id' => $this->workorder->id,
'stream_description_plus' => $this->stream_description_plus,
'manifest_number' => $this->manifest_number,
'manifest_quantity' => $this->manifest_quantity,
'manifest_rate' => $this->manifest_rate,
'manifestable_id' => $this->workorder->id,
'manifestable_type' => get_class($this->workorder)
]);
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function updateManifest($id)
{
$record = Workorder::find($id);
/* dd($record);*/
$record->update([
'stream_description_plus' => $this->stream_description_plus,
'manifest_number' => $this->manifest_number,
'manifest_quantity' => $this->manifest_quantity,
'manifest_rate' => $this->manifest_rate,
]);
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function deleteManifest($id)
{
$record = Manifest::findOrFail($id);
$record->delete();
return redirect()->route('admin.workorder.edit', $this->workorder->id);
}
public function render()
{
$items = Item::all();
$users = User::all();
$projects = Project::all();
$generators = Generator::all();
$customers = Customer::all();
$personnel = Personnel::all();
$streams = Stream::all();
return view('livewire.admin.workorders.edit',
compact('items', 'projects', 'generators',
'customers', 'personnel', 'users', 'streams'));
}
}
update form
...
<form wire:submit.prevent="updateManifest({{$man->id}})" method="PUT">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6">
<select wire:model="stream_id"
class="mt-1 form-select block w-full pl-3 pr-10 py-2 text-base leading-6 border-gray-300 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 sm:text-sm sm:leading-5">
<option value="">
Select Waste Stream
</option>
#foreach($streams as $stream)
<option value="{{$stream->id}}">{{$stream->stream_description}}</option>
#endforeach
</select>
#error('stream_description')
<span class="error">{{ $message }}</span>
#enderror
</div>
</form>
...

multiple data insert into database in laravel

Hi i am new to laravel i am having trouble in inserting data into database and throwing error as
"count(): Parameter must be an
array or an object that implements Countable"
i want to add attendence details of all the registred employees in the databse
controller
public function Attendence()
{
$data=employee_data::all();
return view('attendence',compact('data'));
}
public function mark_attendence(Request $request)
{
$request->validate([
'date' => 'required',
'is_present' => 'required'
]);
$data=$request->all();
$last_id=employee_data::create($data)->id;
if (count($request->is_present) >0 )
{
# code...
foreach ($return->is_present as $item => $v)
{
$data2=array(
'is_present' =>$request->is_present[$item],
'date'=> $request->date[$item],
'user_id'=>$last_id
);
}
//$data2->save();
//$employee->save();
//$employee->employee_data()->create([]);
return redirect('/index')->with('succ','Attendence Added Successfully');
}
Blade output:
Submit
Id
First Name
Last Name
DateOfJoining
post
Remark
#foreach( $data as $row )
{{ $row->id }}
{{ $row->first_name }}
{{ $row->last_name }}
{{ $row->date_joining }}
{{ $row->post }}
&nbsp &nbsp Present
&nbsp &nbsp Absent
#endforeach
Id
First Name
Last Name
DateOfJoining
post
Remark
Model
class employee_attendence extends Model
{
//
protected $fillable = array('is_present' ,'date', 'user_id' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_data(){
//return $this->hasOne(employee_data::class,'App/employee_data');
return $this->hasOne('App\employee_data');
}
}
Model2
namespace App;
use Illuminate\Database\Eloquent\Model;
class employee_data extends Model
{
//protected $fillabel=['first_name','last_name','contact_no','date_joining','post'];
protected $fillable = array('first_name', 'last_name', 'contact_no' ,'date_joining','post' );
//protected $fillable=[];
public $timemstamps= false ;
public function employee_attendence()
{
//return $this->hasOne( employee_attendence::class, 'App/employee_attendence');
return $this->belongsTo('App\employee_attendence');
}
}
As far as I understand. You might have is_present will be an array format from view like name="is_present[]". If this your case then the below code will work fine. if not then you can't use count() if input is not an object or array
public function mark_attendence(Request $request)
{
for($i = 0; $i < sizeof($request->is_present); $i++)
{
$emp = new employee_attendence();
if($request->is_present[$i] == "Present")
$emp->is_present = "Present";
if($request->is_present[$i] == "Absent")
$emp->is_present = "Absent";
$emp->date = now();
$emp->user_id = $request->user_id[$i];
$emp->save();
}
return redirect('/index')->with('succ','Attendence Added Successfully');
}
In your Add Attendance method try this
this worked for me
for($i = 0; $i < sizeof($request->is_present); $i++)
{
$emp = new employee_attendence();
if($request->is_present[$i] == "Present")
$emp->is_present = "Present";
if($request->is_present[$i] == "Absent")
$emp->is_present = "Absent";
$emp->date = $request->date;
$emp->user_id = $request->user_id[$i];
$emp->save();
}

laravel call to a member function categories() on integer

I am trying to update and existing record in pivot table for many to many relationsip with laravel.
I have store function that work :
public function store(Request $request)
{
$produk = new product($request->input()) ;
$feat = (boolean)$request->input('featured');
$input = $request->all();
$input['featured'] = $feat;
$inputproduk = product::create($input);
$inputproduk->categories()->attach($request->input('kat_id'));
return redirect()->back()->with('message', 'Memasukkan Data Produk Berhasil');
}
But why my update function didn't work???
public function update(Request $request, $id)
{
$produk = Product::FindorFail($id);
$produk = new product($request->input()) ;
$input = $request->except('_method', '_token', 'picture', 'kat_id');
$inputproduk = product::whereId($id)->update($input);
$inputproduk->categories()->sync($request->input('kat_id'));
return redirect()->back()->with('message', 'Mengedit Data Produk Berhasil');
}
The error is :
Call to a member function categories() on integer
What is that mean? Please help me.
View :
<div class="form-group">
<label for="KategoriProduk">Kategori Produk</label>
<select class="form-control" name="kat_id[]" multiple>
#foreach($kategoris as $value)
<option value="{{$value->id}}">{{$value->namekat}}</option>
#endforeach
</select>
</div>
I only post partially because if I post it all then the question is just full of code. Tell me if you need more.
It's because of the following line.
$inputproduk = product::whereId($id)->update($input);
When you call update it will return an integer not a product object.
What you can do is first get the product and then update.
$inputproduk = product::whereId($id)->first();
$inputproduk->update($input);
$inputproduk->categories()->sync($request->input('kat_id'));

laravel 5.0 delete and edit in database

How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?
This is my library, here I want to delete or update something from my database
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
<button>Edit</button> <a href="/delete">
<button>Delete</button></a></td>
<!--<td> <button type="delete" name="button"></button>-->
<td>
</td>
</tr>
#endforeach
In your controller (I will assume that you have created), implements this two functions.
public function edit($id) {
// Create a var called `$job` and uses the function `find()` passing into the $id that you clicked before
$job = Job::find($id);
// Return a view with the object that you found into a edit view
return view('jobs.edit', [
'job' => $job
]);
}
public function destroy($id) {
// Use the function `find()` passing into the $id that you clicked before and that use the delete method to delete the job
Job::find($id)->delete();
// Returning into a route that contains the jobs, probably
return redirect()->route('jobs');
}
Read the docs https://laravel.com/docs/5.4/controllers
in your route:
Route::post('delete','CallyourController#delete');
Route::post('update','CallyourController#update');
I think this is what you want to do.
my Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\Jobs;
class JobController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
return view('library',['allJobs' => Jobs::all()]);
}
//my create function
public function create()
{
return view('add');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(Request $request)
{
$job = new Jobs();
$job->jobtitle_de = array_key_exists('jobtitle_de',$_POST) ?
$_POST['jobtitle_de'] : '';
$job->jobtitle_en = array_key_exists('jobtitle_en',$_POST) ?
$_POST['jobt'] : '';
if (array_key_exists('place', $_POST)) {
$places = $_POST['place'];
$placesString = "";
foreach ($places as $p) {
$placesString .= $p.',';
}
$job->location = $placesString;
}
$job->workinghours = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->workinghours_de = array_key_exists('workinghours',$_POST) ?
$_POST['workinghours'] : '';
$job->selected_image= array_key_exists('selected_image',$_POST) ?
$_POST['selected_image'] : '';
$job->grey_header_de = array_key_exists('grey_header_de',$_POST) ?
$_POST['grey_header_de'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->selected_icon = array_key_exists('selected_icon',$_POST) ?
$_POST['selected_icon'] : '';
$job->date;
if (array_key_exists('date',$_POST) && !empty($_POST['date'])) {
$date = $_POST['date'];
$date = explode('/',$_POST['date']);
$newdate = $date[2]."-".$date[0]."-".$date[1];
$job->date = $newdate;
}
$job->grey_header_de = $_POST['grey_header_de'];
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "full-time") {
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Vollzeit";
}
if (array_key_exists('workinghours',$_POST) && $_POST['workinghours']
=== "part-time"){
$job->workinghours = $_POST['workinghours'];
$job->workinghours_de = "Teilzeit";
}
try {
$job->save();
}
catch (Exceptions $e) {
echo $e->getMessage();
}
return redirect()->action('JobController#index');
}
//my edit function
public function edit($id)
{
$job = Job::find($id);
return view('jobs.edit', [
'job' => $job
]);
}
//destroy function
public function destroy($id)
{
Job::find($id)->delete();
return redirect()->route('jobs');
}
now I found this in the internet:
<div class="library">
<table>
#foreach ($allJobs as $job)
<tr>
<td><img src="{{$job->selected_icon}}" width="50" /> </td>
<td>{{$job->jobtitle_de}}</td>
<td>{{$job->location}}</td>
<td><img src="{{$job->selected_image}}" width="100" /></td>
<td>{{$job->workinghours}}</td>
<td>{{$job->grey_header_de}}</td>
<td>{{$job->date}}</td>
<td>
{{ Form::open(['method' => 'DELETE', 'route' => 'job.destroy', $job]-
>id]) }}
{{ Form::hidden('id', $job-id) }}
{{ Form::submit('delete', ['class' => 'library']) }}
{{Form::close}}
</td>
</tr>
#endforeach
and this is my Controller
public function destroy($id)
{
$jobs = Job::findOrFail($id);
$jobs->delte();
return redirect::route('/');
}

Laravel 4 Creating Form for adding record with relationship

I have created very basic Model. I have persons table and emails table.
Also I have create a link in the persons/show.blade.php ("Add mail").
My models are
class Person extends Eloquent {
protected $table = 'persons';
public function email()
{
return $this->HasMany('Email');
}
}
and
class Email extends Eloquent {
protected $table = 'emails';
public static $rules = array(
'email'=>'required|unique:emails'
);
public function person()
{
return $this->belongsTo('Person');
}
}
How can I pass the $person->id to the new Controller?
In my show.blade.php for Person I added
{{ HTML::linkRoute('email.adduseremail','Προσθήκη Email',array($person->id))}}
and I added to my EmailController
public function adduseremail($id)
{
return View::make('email.createforuser',['id'=>$id]);
}
public function storeforuser($pid)
{
$validator = Validator::make(Input::all(),Email::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
foreach ($messages->all('<li>:message</li>') as $message)
return Redirect::back()->withInput()->WithErrors($messages);
}
$person = Person::FindorFail($pid);
$email = new Email;
$email->email = Input::get('email');
$email->person()->associate($person);
$email->save();
return Redirect::route('person.index');
}
and my createforuser view is
<p>
{{Form::open(['route'=>'email.storeforuser'])}}
<div>
{{Form::label('email', 'Email:')}}
{{Form::input('text', 'email')}}
{{$errors->first('email')}}
</div>
</br>
<div>
{{Form::submit('Submit')}}
</div>
{{Form::close()}}
<p>
I keep getting Trying to get property of non-object (View: /var/www/laravel/app/views/email/show.blade.php)
Is there any example using Form and Models for inserting new objects to the database for 'belongsTo' Relationship? I couldn't find anything complete , just partial examples.
I generally use laravel sessions or laravel cache to tempererally save an id that i need to use later like:
Session::set('personId',$person->id);
Session::get('personId');
The same is for cache except cache will only last for the current request session is persistent for the session
Hope that helps
I am no sure if I 'm supposed to answer my own question but finally I found a solution.
I set two new routes
Route::post('email/adduseremail/{pid}', array('uses'=>'EmailController#adduseremail','as' => 'email.adduseremail'));
Route::post('email/storeforuser/{pid}', array('uses' =>'EmailController#storeforuser','as' => 'email.storeforuser'));
and created the corresponding methods in my Controller
public function adduseremail($id)
{
$pname = Person::Find($id)->name;
$psurname = Person::Find($id)->surname;
return View::make('email.createforuser',array('id'=>$id,'name'=>$pname, 'surname'=>$psurname));
}
and
public function storeforuser($pid)
{
$validator = Validator::make(Input::all(),Email::$rules);
if ($validator->fails())
{
$messages = $validator->messages();
foreach ($messages->all('<li>:message</li>') as $message)
return Redirect::back()->withInput()->WithErrors($messages);
}
$person = Person::FindorFail($pid);
$email = new Email;
$email->email = Input::get('email');
$email->person()->associate($person);
$email->save();
return Redirect::route('person.show',array($person->id));
}
then on my view blade pages I can pass the parameters from View to Form and so on
person.show.blade.php
{{Form::Open(array('route' => array('email.adduseremail', $person->id),'method' => 'POST','style'=>'display:inline;'))}}
{{Form::submit('Add Email')}}
{{Form::close()}}
and
email.createforuser.blade.php
{{Form::open(array('route'=>array('email.storeforuser',$id),'method' => 'POST','style'=>'display:inline;'))}}
{{Form::label('email', 'Email:')}}
{{Form::input('text', 'email')}}
{{Form::submit('Submit')}}
Hope it helps others also

Categories