I have a dropdown list in a data capture view where a join is used in the Controller, but when I am trying to save the record, I am getting a below error.
Method Illuminate\Support\Collection::save does not exist.
I have tried to change the eloquent statement to
$energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();
instead of
$energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();
however that gives me a below error.
Call to undefined method stdClass::save()
Does anyone know what the correct one is?
Controller:
public function index()
{
// $energy = Maintenance::orderBy('id', 'desc')->paginate(5);
$energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->get();
$cars = Vehicle::get();
$staff = Staff::all();
return view('admin.vmaintenance', compact('energy', 'cars', 'staff'));
}
public function store(Request $request)
{
// $energy = new Maintenance;
$energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();
$cars = Vehicle::all();
$staff = Staff::get();
$energy->staff_key = $request->input('staff_key');
$energy->vehicle_id = $request->input('vehicle_id');
$energy->log_dt = $request->input('log_dt');
$energy->admin_time = $request->input('admin_time');
$energy->driving_time = $request->input('driving_time');
$energy->work_time = $request->input('work_time');
$energy->jobcard_count = $request->input('jobcard_count');
$energy->start_odo = $request->input('start_odo');
$energy->end_odo = $request->input('end_odo');
$energy->save();
return redirect('/vmaintenance')->with('success', 'data added');
}
View:
<label>Select Vehicle</label>
<select name="vehicle_id" >
#foreach($cars as $car)
<option value="{{ $car->id }}">{{ $car['reg_number'] }}</option>
#endforeach
</select>
Eager loading:
$energy = VehicleLog::with('vehicle')->first();
Also:
this variable never used in your store() action:
$cars = Vehicle::all();
$staff = Staff::get();
you can use fill() method:
$energy->fill($request->only([
'staff_key', 'vehicle_id', 'admin_time',
'driving_time', 'work_time', // ...
]));
Since you aren't using a model you'll need to just use an insert statement.
DB::table('vehicleslog')->insert([
'staff_key' => $request->input('staff_key'),
'vehicle_id' => $request->input('vehicle_id'),
'log_dt' => $request->input('log_dt'),
// etc........
)];
Related
I am creating property website and i am doing search with number of attributes, but the problem is that in search controller i have very large code and its very difficult to handle, is there any other solution exist in laravel?
$list_property = Listing_property::where([
['property_type', $request['property_type']],
['city', $request['city']],
['location', $request['location']],
['property_area_type', $request['property_area_type']],
['property_size', $request['property_size']],
['price', $min],
['price', $max]
])
->orderBy('updated_at', 'DESC')
->paginate(21);
The easiest way to search multiple column :
public function search(Request $request){
$query = $request->search;
$users = DB::table('users');
if($query){
$users = $users->where('name', 'LIKE', "%$query%");
}
if($request->city){
$users = $users->where('city',$request->city);
}
if($request->town){
$users = $users->where('town', $request->town);
}
if($request->unit){
$users = $users->where('unit', $request->unit);
}
$users->get();
return view('users.index')->with('users', $users);
}
I am trying to query two tables in Laravel when the user submits a form. The data is stored in the transaction table and I can also update the Account table by adding the $transactions->amt with $account->total.
I tried doing this;
public function store(Request $request)
{
$account = DB::table('users')
->join('accounts', "users.id", '=', 'accounts.user_id')
->select('users.*', 'accounts.*')
->first();
$transaction = new Transaction();
$data = $this->validate($request, [
'baddress'=>'required',
'package'=>'required',
'amt'=>'required',
]);
$transaction->username = $account->username;
$transaction->baddress = $request->input('baddress');
$transaction->package = $request->input('package');
$transaction->amt = $request->input('amt');
$transaction->fund_option = "Fund";
$transaction->save();
$bal= $transaction->amt + $account->total;
$account->amt_paid = $bal;
$account->total = $bal;
$account->save();
return redirect('/transfer')->with('success', 'Transaction has been made');
}
but I got this error:
Call to undefined method stdClass::save()
How can I find the best method to do this?
That error occur because $account is not collection. method save() is method from model collection.
if you want update you can use this code like.
$accountUpdate = DB::table('accounts')
->where('id', $account->id)
->update(['amt_paid' => $bal, 'total' => $bal]);
but if you want to use method save() then you have to call $account from model.
$account is a row made by your join (users.* and accounts.*) so it's a stdClass, not an Eloquent model. You don't have a save() method
in order to do this you should have a relationship between User model and Account model:
//Account.php
public function user(){
return $this->belongsTo("App\User");
}
........
//User.php
public function account(){
return $this->hasOne("App\Account");
}
then you can retrieve Account from your User:
$user = User::first();
$account = $user->account;
[....]
$account->amt_paid = $bal;
$account->total = $bal;
$account->save();
You have to use like this. This is simple as like as much
$accountModelUpdate = DB::table('accounts')
->where('user_id', $account->id)
->update(['amt_paid' => $bal, 'total' => $bal]);
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 );
}
}
I'm thinking why I can't insert or save the tables that I groupBy in the statement that I did. I group them properly but when I tried to insert this into my database it just get the first value in the column not all the values. I have a one to many relationship between departments and users
Die and Dump
As you can see here in "Department of Engineering" I have a users id which is 3 and 4. When I tried to insert this into database the first value is only that inserted.
Database Values
Controller
public function getDocuments()
{
$departmentRecipient = DB::table('users')->select('departments.department_name', 'users.id', DB::raw('group_concat(users.id)'))
->join('departments', 'departments.id', '=', 'users.department_id')
->groupBy('departments.department_name')
->get();
}
public function postDocuments(Request $request)
{
$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 );
}
}
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>
In my database I have two models, User and Role defined as many-many relationship, I'm trying to write a code in laravel that takes the id from the roles table and gets all the user fullnames from the users table.
I have defined a route that looks like this :
Route::get('roleUser/{role}', 'RoleController#RoleNames');
in which i pass the role name with it, as you see above
In my RoleController, I defined the method roleNames to do the job
public function RoleNames($role)
{
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->first()->id;
$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get(array('id'));
$usersUnderRole = array();
foreach ($iduser as $idusers) {
$usersUnderRole = array_add($usersUnderRole, $idrole, $idusers);
$full_name = DB::table('users')->where('id', '=', $idusers)->get()->full_name;
}
return $this->respond([
'result' => $this -> roleTransformer->transform($full_name)
]);
}
This code is meant to take the role_id from the roles table and gets the appropriate user_ids by the pivot table assigned_roles, puts them in an array and fetches the correspondent full_names, but it says this error:
Object of class stdClass could not be converted to string
Any advice on how to get it to work?
This will give you all the users who belong to the given role:
$role_id = 3;
$result = DB::table('role_user')
->select('users.full_name')
->where('role_user.role_id', $role_id)
->leftJoin('users', 'users.id', '=', 'role_user.user_id')
->get();
var_dump($result);
$full_names = DB::table('users')->where('id', '=', $idusers)->lists('users.full_name');
Besides the solution #lamzazo provided, there is another way to go with the answer :
$role2 = Role::where('name', '=', $role)->first();
$idrole = Role::where('name', '=', $role)->first()->id;
//$iduser = DB::table('assigned_roles')->where('role_id', '=', $idrole);
$user = DB::table('assigned_roles')->where('role_id', '=', $idrole)->get();
// $user = DB::table('users')->where('id', '=', $iduser);
// return $this->respond($iduser[0]->user_id);
$userArray = array();
$i=0;
foreach ($user as $users) {
$iduser= $users->user_id;
$allusers = User::where('id', '=', $iduser)->get(array('id', 'full_name'));
$userArray = array_add($userArray, $i . '', $allusers);
$i++;
}
return $this->respond([
'result' => $this -> roleTransformer->testTransform($role2, $userArray)
]);