Laravel How to find Mutual Friends from model? - laravel

I am using laravel 8.
I want to find the mutual friends of entries and profiles.
Please ask me if it is not clear...
My friends table;
user_friends;
id | user_id | user_friend_id
1 | 10 | 20
2 | 20 | 10
In My User Model;
public function friends(){
return $this->belongsToMany(User::class, 'user_friends', 'user_id', 'user_friend_id');
}
public function friendsOf(){
return $this->belongsToMany(User::class, 'user_friends', 'user_friend_id', 'user_id');
}
How can I find mutual friends of the profile with respect to authenticated user?
Example;
#foreach($user as $entry)
{{ count( $entry->mutual(Auth::id()) ) }}
#foreach($entry->mutual(Auth::id()) as $item)
{{ $item->name }}
...
#endforeach
#endforeach

I make this work by using helpers. I create helpers.php on App folder and create a function.
function mutualFriends($id){
$profile = User::where('id', $id)->first();
$profileFriends = $profile->friends;
$profileFriendsIds = [];
foreach ($profileFriends as $entry){
$profileFriendsIds[] = $entry->id;
}
$loggedUserFriends = Auth::user()->friends->whereIn('id', $profileFriendsIds);
return $loggedUserFriends;
}
and now I am calling the function from view like;
{{count(mutualFriends(Auth::id()))}}
or
#foreach(mutualFriends($profile->id) as $entry)
...
#endforeach

Related

laravel controller returns only 2 values

I have a database with 3 tables. A separate model is connected to each table, and there is a controller that accepts values from all models. On the site page, I will have 3 tables that will be populated from a mysql table.
When I connected 2 models, everything worked fine. But after connecting 3, I get an error
undefined variable: sec_3.
If you delete one of the variables, then everything will work fine. It seems to me that the problem is either with the controller or with the file blade.php but I do not know how to fix it so that everything works properly. How to fix it?
My code:
Controller:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context=['bbs' =>PreschoolInstitution3::latest()->get()];
$context_2=['s' =>PreschoolInstitution::latest()->get()];
$context_3=['sec_3' => TrainingPrograms::latest()->get()];
return view('our_employees', $context, $context_2, $context_3);
}
}
web.php:
Route::get('/OurEmployees',[PreschoolInstitution3Controller::class,'index'] )->name('OurEmployees');
blade.php:
#foreach ($s as $section_2) <tr> <td>{{$section_2->number}}<td> <td>{{$section_2->fullname }}<td> <td>{{$section_2->post }}<td> <td>{{$section_2->telephone }}</td> <td>{{$section_2->email }}</td>
#endforeach #foreach ($bbs as $section )
{{$section->number}} {{$section->full_name}} {{$section->post}} {{$section->education}} {{$section->category}} {{$section->teaching_experience}} {{$section->professional_development}}
#endforeach #foreach ($sec_3 as $section_3)
{{ $section_3->number }}
{{ $section_3->level }}
{{ $section_3->directions }}
{{ $section_3->type_of_educational_program }}
{{ $section_3->period_of_assimilation }}
{{ $section_3->number_of_students }}
#endforeach
You should pass an array of data to view:
class PreschoolInstitution3Controller extends Controller {
public function index(){
$context = [
'bbs' => PreschoolInstitution3::latest()->get(),
's' => PreschoolInstitution::latest()->get(),
'sec_3' => TrainingPrograms::latest()->get()
];
return view('our_employees', $context);
}
}
https://laravel.com/docs/9.x/views#passing-data-to-views
Another one is that add a second parameter of an array with name to view( ) .
class PreschoolInstitution3Controller extends Controller {
public function index(){
$bbs = PreschoolInstitution3::latest()->get();
$s = PreschoolInstitution::latest()->get();
$sec_3 = TrainingPrograms::latest()->get();
return view('our_employees', [
'bbs' => $bbs,
's' => $s,
'sec_3' => $sec_3
]);
}
}

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

I want to fetch an questions by id and it has multiple answers

I have Question model that has many answers
class Question extends Model
{
public function answers()
{
return $this->hasMany('App\Answer');
}
}
also I have Answer model , in this each answer belong to a question.
class Answer extends Model
{
//
public function question()
{
return $this->belongsTo('App\Question');
}
}
So what i am trying to do is I want to fetch a question by it's id and it should have all the answers that belong to this particular question and together I want to pass it to my view.
Here is what I have Done so far
public function show($id)
{
$questions = Question::with('questions')
->join('answers', 'answers.question_id' , '=' , $id)
->select('questions.id',
'questions.ask_question',
'answers.user_id',
'answers.aanswer',
'answers.created_at')
->where('questions.id' , '=', 'answers.question_id')
->get();
return view('pages.show', ['questions' => $questions , 'user' => Auth::user()]);
}
I have tried several other way but that didn't work
You can just fetch the question and use the relation in the view.
public function show($id)
{
$question = Question::find($id);
if ( ! $question) {
abort(404);
}
return view('pages.show', compact('question'));
}
And in your model you can do something like:
<h2>{{ $question->question }}</h2>
<ul>
#foreach ($question->answers as $answer)
<li>{{ $answer->answer }}</li>
#endforeach
</ul>
Btw, there's no need to assign the Auth::user() to the view, the Auth facade is available there as well. You can also just use the helper method auth().
<p>{{ Auth::user()->email }}</p>
or
<p>{{ auth()->user()->email }}</p>
Will work just fine.

Loop through nested relation in view

I'm trying to loop through some data in my blade view. This is my database setup:
What I would like to have in my view is the following:
So I can loop through the days and then order the tasks by the category they are in. I'm not experienced with Laravel and I'm having difficulties on ordering the tasks by category in the best way.
In my Days Model I have:
public function tasks()
{
return $this->belongsToMany('App\Task');
}
In my Task Model I have:
public function days()
{
return $this->belongsToMany('App\Day');
}
public function category()
{
return $this->belongsTo('App\Category');
}
In my Category Model I have:
public function tasks()
{
return $this->hasMany('App\Task');
}
In my controller I now only have:
public function index()
{
$categories = Category::all();
return view('app.blade.php', compact('categories'));
}
But how can I make sure to order them by days and then by category? Help much appreciated.
You can try as following:
$days = Days::with('tasks.category')->get();
$days = $days->map(function ($day) {
$day->tasks = $day->tasks->groupBy('category_id');
return $day;
});
Check it how it is converted after groupBy() method
dd($days);
then in your view you can do as:
#foreach ($days as $day)
{{ $day->name }}
#foreach ($days->tasks as $tasks)
{{ $tasks->first()->category->name }}
#foreach ($tasks as $task)
{{ $task->name }}
#endforeach
#endforeach
#endforeach
Note - I have not tested it but you can give it a try.

how do I get the updated_at and created_at

I'm making my first Larevel (4) application and I want to display the date that it was created and I'm getting this problem: Unexpected data found. Unexpected data found. Unexpected data found. Data missing
when I try to do this in my blade template
#extends('layout')
#section('content')
<h3>Name: {{ $user->name }}</h3>
<p>Email: {{ $user->email }}</p>
<p>Bio: {{ $user->bio }}</p>
#endsection()
#section('sidebar')
<p><small>{{ $user->created_at }}</small></p>
#endsection()
#stop
and my controller
<?php
class UserController extends BaseController
{
public $restfull = true;
public function get_index() {
//$users = User::all();// gets them in the order of the database
$users = User::orderBy("name")->get(); // gets alphabetic by name
$v = View::make('users');
$v->users = $users;
$v->title = "list of users";
return $v;
}
public function get_view($id) {
$user = User::find($id);
$v = View::make('user');
$v->user = $user;
$v->title = "Viewing " . $user->name;
return $v;
}
}
?>
it works as soon as I take out :
<p><small>{{ $user->created_at }}</small></p>"
any ideas how to access those values, I checked and they DO exist in my table.
this is the schema of my table
CREATE TABLE "users" ("id" integer null primary key autoincrement, "email" varchar null, "name" varchar null, "bio" varchar null, "created_at" datetime null, "updated_at" datetime null);
So here's what I did to fix it.
in the migrations I did this:
class CreateTable extends Migration {
public function up()
{
Schema::create('users', function($table) {
$table->string('name');
$table->timestamps();
});
}
/* also need function down()*/
I had the insertions like this in my migrations to add some users.
class AddRows extends Migration {
/* BAD: this does NOT! update the timestamps */
public function up()
{
DB::table('users')->insert( array('name' => 'Person') );
}
/* GOOD: this auto updates the timestamps */
public function up()
{
$user = new User;
$user->name = "Jhon Doe";
$user->save();
}
}
Now when you try to use {{ $user->updated_at }} or {{ $user->created_at }} it will work! (assuming that you passed $user to the view)
There are a few things going on here that should probably be fixed. Since this is a restful controller, Laravel expects your function names to be camelCase rather than snake_case.
The way you are passing variables to the view also is not looking right. Try passing the $users variable to the view with return View::make('users')->with('users',$users);.
Another thing is you are passing a collection of users to the view, which means you won't just be able to echo user information. To get the user information out of the collection, you must iterate through the collection with a loop. (Your app will probably break again once you get more than one user in)
foreach($users as $user)
{
echo $user->name;
echo $user->email;
echo $user->bio;
}
Because the way you have your sidebar and content sections showing user information, what you probably actually want to do to get your user is something along the lines of $user = User::find(Auth::user()->id); meaning it would be returning one user and you'd be able to lose the loop.
One more thing I just seen. If you are setting up a restful controller, the proper property is public $restful = true; though I'm not sure that's actually being used anymore because you are basically setting that in routes.php with Route::controller('user', 'UserController');.

Resources