laravel call to a member function categories() on integer - php

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'));

Related

how to create laravel dynamic single row value

i am trying to create single row dynamic drop-down. give me reference or give me example.
my table
I NEED THIS ANSWER IN DROP DOWN
if I understand your question then I think this can ve the correct answer
public function data(){
$datas = Model::all();
return view('your view name',compact('datas'));
}
in your blade
<form action="{{url('YourUrlforFormSubmit')}}">
<select name="product">
foreach($datas as $data)
<option value="{{$data->id}}">{{$data->name}}</option>
</select>
</form>
in web.php
Route::post('YourUrlforFormSubmit','YourController#saveData')
in controller
public function saveData(Request $request){
$data = Model::find($request->id);
$save = new YournewModel; //whereyou want to save the data
$save->part_id = $data->part_id;
$save->name= $data->name;
$save->price= $data->price;
$save->save();
return view('your view name',compact('datas'));
}

How to store array in Laravel?

There are two mysql tables 1.seats (id,number), 2.reservedseats(id,seat_id,sceering_id).
I show all the seats of a specific sceering as checkboxes in show.blade:
{!!Form::model($screening,['method'=>'post', 'action'=>
['ReserveController#store',$screening->auditorium->id]])!!}
<input type="hidden" name="screening_id" value="{{$screening->id}}">
#foreach($seats as $seat)
<label class="checkbox-inline">
{!!Form::checkbox('seat_id[]',$seat->id,null)!!} Number: {{$seat->number}}
</label>
#endforeach
<div class='form-group'>
{!!Form::submit('Create Post',['class'=>'btn btn-primary '])!!}
</div>
{!!Form::close()!!}
When I click a checkbox it goes the the seat_id[] array. So I send a hidden input and an array with the seat_ids then I want to store in the reservedseats Mysql table. But in the store controller I have the problem. I'm trying something like:
public function store(Request $request){
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
foreach($seat_ids as $seat_id){
Seatreserved::create($seat_id,$screening_id);
}
}
So it not working but how can I solve that?
Try this code
public function store(Request $request)
{
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
foreach($seat_ids as $seat_id) {
Seatreserved::create([
'seat_id' => $seat_id,
'screening_id' => $screening_id
]);
}
}
Also you can use
public function store(Request $request)
{
$screening_id = $request->screening_id;
$seat_ids = $request->seat_id;
$data = [];
foreach($seat_ids as $seat_id) {
$data[] = [
'seat_id' => $seat_id,
'screening_id' => $screening_id
];
}
Seatreserved::insert($data);
}
That is better way to perform this as it will interact with database for once.
You can also create a new instance of your model to store values.
Example:
foreach($seat_ids as $seat_id) {
$reserved = new Seatreserved();
$reserved->seat_id = $seat_id;
$reserved->screening_id = $screening_id;
$reserved->save();
}

groupBy only gets the first id

I have a many to many relationship between departments and users my pivot table is department_user. I wanted to select all the department_name depending of the user's department using groupBy method to merge all the department_name into one. See below my statement.
$departmentRecipient = DB::table('users')->select('departments.department_name', 'users.id')
->join('department_user', 'users.id', '=', 'department_user.user_id')
->join('departments', 'department_user.department_id', '=', 'departments.id')
->groupBy('departments.department_name')
->get();
Result using die and dump.
As you can see here I have an id of 4 under "Department of Engineering". My main problem is it doesn't fetch all the id under "Department of Engineering". But in my SQL I have id of 5 not only 4. How can I solve this problem? Any help would greatly appreciated. Please see result below.
Output:
This is the output of my list. I wanted to get all the users id belongs to the specific option for the user. But if I choose "Department of Engineering" it only gets the id of 4 not 5. I wanted to get 4 and 5 once.
Controlller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
return view ('document.create')->with('departmentRecipient', $departmentRecipient);
}
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
'content' => 'required',
'category' => 'required',
'recipient' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
$user = Auth::user();
foreach($request->recipient as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}
Model
User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Department
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
View
<div class = "form-group">
<label for = "recipient" class = "control-label">Recipient:</label>
<select name = "recipient[]" multiple class = "form-control select2-multi" id = "myUserList">
#foreach ($departmentRecipient as $list)
<option value = "{{ $list->id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
From your given code it seems you are not using Eloquent ORM, you are doing it using Query Builder.
If you don't have a performance concern right now you can do it using separate queries. Like-
$departmentRecipient = DB::table('departments')->all();
foreach($departmentRecipient as $department){
$department->users = DB::table('department_user')->where('department_id',$department->id)->pluck('user_id');
}
But the better way is to use the eloquent with relationships. Define the many to many relationship in your eloquent model of Users and Departments (assuming you have eloquent model for them). You will find details about eloquent relationships at laravel documentation.
Update:
From the update of your post it is actually pretty easy to do what you want. If your Request contains the selected department id then you can do the following:
public function postDocuments(Request $request)
{
$document = new Document();
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
//get the users list of the selected department id
$selected_department = $request->department_id; //this must be included in your POST data
$users = DB::table('department_user')->where('department_id',$selected_department)->pluck('user_id');
//now you have the list of the users id
foreach($users as $user){
// do what you need here
}
}
Update 2:
Following controller code might work for you.
Controller:
public function getDocuments()
{
// I am suggesting here to change the '$departmentRecipient' to '$departmentlist', as it is more meaningful. Also in your view
$departmentlist = DB::table('departments')->get();
return view ('document.create')->with('departmentlist', $departmentlist);
}
public function postDocuments(Request $request)
{
//same as you have till the $document->save()
....
....
//then do this
$recipients = array();
$departments = $request->recipient;
foreach($departments as $department){
$users = DB::table('department_user')->where('department_id',$department)->pluck('user_id');
$recipients = array_merge($recipients, $users);
}
//now you have a complete list of the users from selected departments
//Do as you intend to like this
$user = Auth::user();
foreach($recipients as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}

Updating database with laravel

Let me explain situation, person is searching through skills and when clicked displays list of handymans with that skill, when user clicks on one of them, full details are displayed. user then clicks assign job link and is taken to a page with jobs along with checkbox and when desired job is chosen, and submit button clicked, I want a database to update "job_id" value in "handymen" database. How could that be done?
#extends('layouts.master')
#section('title', 'Assign Job')
#section('content')
#section('content')
<form action="{{url('assignjob')}}" method="POST">
{{ csrf_field() }}
#foreach ($jobs as $job)
<div>
<label>{{$job->name}}</label>
<input type='checkbox' value='{{$job->id}}' name='jobs[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Assign Job">
</form>
#endsection
function search()
{
$skills = Skill::all();
return view('layouts/search',['skills' => $skills]);
}
function details($skillId)
{
$skill = Skill::find($skillId);
$handymen = $skill->handymen;
return view('layouts/details', ['skill' => $skill,'handymen' => $handymen]);
}
function assignJob($handymanId)
{
$assignJob = Hadnyman::find($handymanId);
$jobs = Job::all();
return view('layouts/assignjob',['jobs' => $jobs]);
}
function jobassign(Request $request)
{
return redirect('assignjob');
}
function skilledHandyman($handymanId)
{
$skilledHandyman = Handyman::find($handymanId);
return view('layouts/skilledHandyman', ['skilledHandyman' => $skilledHandyman]);
}
If a specific code is needed, please let me know
You should look at Eloquent Relationship.
Handymen has many Job
class Handymen extends Model {
...
public function jobs() {
return $this->hasMany(App\Job::class);
}
}
In your controller
function assignJob(Request $request, $id)
{
$handymen = Handyman::findOrFail($id);
// $request->get('jobs') = [1, 6, 7, etc...]
$handymen->saveMany($request->get('jobs'));
return ...;
}

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

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

Categories