Model Structure
user.php
public function inventories() {
return $this->belongsToMany('App\Model\user\inventory')->orderBY('created_at','DESC')->paginate(10);
}
inventory.php
public function users() {
return $this->belongsToMany('App\Model\user\user')->withTimestamps();
}
Table Structure:
inventories:
id
user_id
content
users:
id
name
email
How to call the inventories->user_id to connect in users->id in controller?
Example in laravel blade:
user_id = 1
content = 'This is content'
I want is:
user_id = 'Name of user 1'
content = 'This is content'
Since you have defined your relations, you can use :
$inventories = Inventory::all();
foreach ($inventories as $inventory) {
foreach ($inventory->users as $user) {
echo $user->name; // show the name of user
}
// or to get first user :
$user_1_name = isset($inventory->users[0]) ? $inventory->users[0]->name : '-';
}
On your controller:
$inventories = Inventory::all();
On your blade file:
#foreach ($inventories as $inventory)
{{ $inventory->users()->id }}<br/>
#endforeach
Related
I have problem extracting the data into html file, The data are from database and it's already encode in the Controller of Laravel, So now the problem how to extract the data into my customer_data.blade.php using Fetch of javascript
I have here the public function customer:
public function customer() {
$select_menu = DB::select('SELECT menu_cat_id,menu_cat_name,menu_cat_desc,menu_cat_price,menu_cat_image FROM menu_category WHERE menu_cat_status = ?',[
'Active'
]);
$select_menu_decode = json_decode(json_encode($select_menu),true);
dd($select_menu_decode);
}
My customer_data public function:
public function customer_data() {
return View('customer_data');
}
You pass in data as an array as described in the docs
public function customer_data() {
$select_menu = DB::select('SELECT menu_cat_id,menu_cat_name,menu_cat_desc,menu_cat_price,menu_cat_image FROM menu_category WHERE menu_cat_status = ?',[
'Active'
]);
return View('customer_data', ['menu'=>$select_menu]);
}
which you would then be able to access in the view template as:
#foreach( $menu as $item )
<li>{{ $item->menu_cat_name }}</li>
#endforeach
I have a user, student and subject model and I want to register a student into many subjects. So I created a StudentRegistration controller and in my create view I show all the subjects that belong to the course of the current logged in user.
StudentRegistration.php create function
public function create()
{
$user_id = Auth::user()->id;
$student_id = Student::where('user_id', $user_id)->first();
$course = $student_id->course->id;
$subjects = Subject::where('course_id', $course)->get();
return view('student.create', compact('subjects'));
}
In the create template I show all the subjects as checkbox because a user can register for multiple subjects.
{!! Form::open(['method' => 'POST', 'action'=>'StudentRegistration#store', 'files'=>true]) !!}
#foreach($subjects as $subject)
<div class="label-box">
{!! Form::label('name', $subject->name) !!}
{!! Form::checkbox('subject_id[]', $subject->id, null, ['class'=>'form-control']) !!}
</div>
#endforeach
<div class="form-group">
{!! Form::submit('Create User', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I have this in my Student.php for the many to many relationship:
public function subjects()
{
return $this->belongsToMany('App\Subject');
}
I created a pivot table named Student_Subject. So, during the store, how can I save all the selected subjects into pivot table (student_subject).
I tried using this:
public function store(Request $request)
{
$data = $request->except('_token');
$subject_count = count($data['subject_id']);
for($i=0; $i < $subject_count; $i++){
$student = Student::where('user_id', Auth::user()->id);
$student->subjects()->attach($data['subject_id'][$i]);
}
}
But I get the following error:
"Method Illuminate\Database\Query\Builder::subjects does not exist."
And how can I view all the course subjects which the student is not registered at?
I have this:
Route::get('/studentsubjects', function(){
$student_id = Student::where('user_id', Auth::id())->first();
$course = $student_id->course->id;
$subjects = $student_id->subjects;
echo 'Registered at' .'<br>';
foreach ($subjects as $registered) {
echo $registered->name .'<br>';
}
$unregistered = Subject::where('course_id', $course)->except($subjects);
});
And see this error:
"Method Illuminate\Database\Query\Builder::except does not exist."
$student = Student::where('user_id', Auth::user()->id);
is not enough to get the Student model, you're only getting the query object here.
In order to actually get the student, use the following:
$student = Student::where('user_id', Auth::user()->id)->first();
Even better if user_id is the primary key for your model Student:
$student = Student::find(Auth::user()->id);
As a side note, you can access directly the user ID from the Auth interface using Auth::id() instead of Auth::user()->id, resulting in:
$student = Student::find(Auth::id());
I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:
public function index(User $id)
{
$user = User::find($id);
$record = $user->diary;
return view('home')->with('record', $record);
}
The blade file it should display to:
#foreach ($record as $diary)
{{ $diary->error }}
{{ $diary->fix }}
#endforeach
In your index function the $id is not integer - this is a User instance, so you can try use this:
public function index(User $user)
{
$record = $user->diary;
return view('home')->with('record', $record);
}
I've made this project using the messages panel, and I want to display the message for a specific person. My relations:
In user:
public function Message()
{
return $this->belongsToMany('App\Message');
}
In message:
public function user()
{
return $this->belongsTo('App\User');
}
And in my controller its look like:
public function wiadomosci()
{
$menuClasses = ['', '', '', 'active', ''];
$messages = Message::where('to_id','=', Auth::user()->id);
return view('panel.wiadomosci', compact('menuClasses'))->with('messages', $messages);
}
When I add where in $message it does not display anything to me, but when I delete it, it shows me all of the messages not assigned to that user.
##Everything is fine now, problem solved. But I have a new problem: I would like to display the user name who send message(teacher_name) in the view, but I can only display an Id. controller:
public function wiadomosci()
{
$menuClasses = ['', '', '', 'active', ''];
$messages = Message::where('to_id','=', Auth::user()->id)
->join('teachers', 'messages.from_id', '=','teachers.id')
->get();
return view('panel.wiadomosci', compact('menuClasses'))->with('messages', $messages);
}
and in view :
#foreach($messages as $message)
Od:{{$message->teachers_name}}
</br>
Tytuł:{{$message->title}}
</br>
opis:{{$message->contents}}
</br>
#endforeach
In mysql query would look like this :
SELECT teachers.name FROM messages JOIN teachers ON messages.from_id=teachers.id
I'm trying to pass a variable from foreach to my view. So I can access this using in my select form. Because I have two tables M:M relationship between departments and user. I need to get all the department_name where the user_id belong. For me able to send a data via department_name Here what I did please take a look.
DB Diagram:
department_user
As you can see here user_id is the id of the user and document_id is where the users belong.
Model:
Department:
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
User:
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
return view('document.create')->with('department', $department);
}
I'm getting all the users_id when I die and dump my variable departmentRecipient.
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 ($department as $list)
<option value = "{{ $list->user_id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
I wanted to foreach the $department in my Controller to my select form. But it always says.
Trying to get property of non-object (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\document\create.blade.php)
Goal:
Use the following loop to iterate through the department users and add them to pivot table.
foreach($request->department as $departmentId)
{
foreach(Department::find($departmentId->id)->users()->get() as $user1) //find the users belonging to the current department
{
$document->sentToUsers()->sync([ $user1->id => ['sender_id' => $user->id]],false );
}
}
Also remove the following code form your getDocuments() as it is redundant:
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
I don't see user_id property in your dumped value of $departmentRecipient object, that is why you are getting the error you mentioned. However, there is a users array inside of $departmentRecipient object, which you made inside your foreach loop. You are plucking every user_id which are in individual department and setting in a property named users of $departmentRecipient object, and so you are getting an array inside users property. Here I have a solution for you,
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
$departmentUsers = array();
foreach ($departmentRecipient as $department)
{
$users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
foreach ($users as $userId) {
$departmentUsers[$userId] = $department->department_name;
}
}
return view('document.create')->with('department', $department)->with('departmentUsers', $departmentUsers);
}
and inside of your view loop through the variable $departmentUsers, like this,
#foreach ($departmentUsers as $userId => $departmentName)
<option value = "{{ $userId }}">{{ $departmentName }}</option>
#endforeach
This will work but as your department contains multiple users so you will get individual department name multiple time in your select2 dropdown. If you share more of what is your goal by select2 then may be I can help you to solve your problem in other way.
Moreover if you are interested to use of Eloquent then you can get rid of lots of foreach looping.
In your case you can have multiple users against each department. So to make it work correctly with your forearch code. You need to make sure you are getting one user record against each depart. So modify following line of code in controller.
$department->users = DB::table('department_user')->where('department_id', '=', $department->id)->pluck('user_id');
But you want to display all users of department then you have to change foreach loop code into view.
Try This Code
App/Department
public function users()
{
return $this->belongsToMany('App\Entities\User', 'department_user', 'user_id', 'department_id');
}
App/User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller
use App/User;
public function getDocuments($userId,User $User)
{
$getSpecificUser = $User->with('departments')->find($userid);
return view('document.create')->compact('getSpecificUser');
}
View
#foreach ($getSpecificUser as $getUser)
#if(empty($getUser->departments) === false)
#foreach ($getUser->departments as $departments)
<option value = "{{ $getUser->id }}">{{ $departments->department_name }}</option>
#endforeach
#endif
#endforeach