How to avoid adding duplicate of element.Laravel, PHP - php

Shortly, there are teachers and i have to attach them courses. Every course should be added once only(not twice). My code is working but only for element with id=1.And the other courses can be attached to a teacher more than once. I am writing the code in laravel. (php).
I can't uderstand why it is working only for the first element(course($id=1)).
Can you help me please. Where is my mistake?? Thank You in advance.
Here is my code. To One Teacher, many different courses should be attached. But not one course twice!
public function addCourse($id, Request $request) {
$teacher = Teacher::findOrFail($id);
if($teacher->has('courses')->where('id', $request->get('course_id'))->get()->isEmpty()) {
$teacher->courses()->attach($request->get('course_id'));
}
else {
flash()->error('This Course has been added already!')->important();
}
return back();
}

I believe there is an issue in how you are querying.
When you do this...
$teacher->has('courses')->where('id', $request->get('course_id'))
That ->where() is still looking at the teachers table, not the courses table. I think what you really want to do is use a whereHas to determine if the teacher has that course.
$hasCourse = Teacher::whereHas('courses', function($q) use ($request) {
// Here we can add constraints on the courses table
$q->where('id', $request->get('course_id'));
})->where('id', $id)->exists();
if (! $hasCourse) {
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($id);
}

PROBLEM SOLVED. I used
$teacher->courses()->sync([$request->get('course_id')],$detaching =
false);
Finally i have this script:
> public function addCourse($id, Request $request) {
> $teacher = Teacher::findOrFail($id);
> $teacher->courses()->sync([$request->get('course_id')],$detaching =
> false);
>
> return back();
> }
Thank you all.

To attach a one to many
$teacher = Teacher::findOrFail($id);
$course = Course::findOrFail($request->get('course_id'));
$course->teacher()->associate($teacher);;
$course->save();

Related

How to use WHERE CLAUSE in Codeigniter 4

Hello i have 2 tables Student & Faculty
i want to call them to my index(view), So I figured how to join them. but I have a problem, I need to divide these 2 tables into a category but I don't know the code. Can someone please help me?
public function getStudentReguler()
{
return $this->db->table('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', *i want to be like, where categor = A*)
->get()->getResultArray();
}
thank you
public function getStudentReguler()
{
return $this->db->table('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', 'A')
->get()->getResultArray();
}
Please try this:
$this->db->select('*')
->from('student')
->join('faculty', 'faculty.id_faculty = student.id_student')
->where('category', 'A')
->get()->getResultArray();

How to join table with req->id

public function getTourDetail(Request $req)
{
//Get link detail
$tour = Tour::where('id',$req->id)->first();
//I want to take location.city of the location table
$detail = Tour::join('location','tour.id_location','=','location.id')
->whereColumn([
['tour.id_location','=','location.id']
])
->get(array(
'tour.id as id_tour',
'location.image',
'tour.name',
'tour.id_location',
'location.city'
));
return view('page.tour-detail',compact('tour','detail'));
}
I would like to be able to combine two query statements to get information from the location table ($ detail) like the id of the link request ($ tour).
Since you use models, you can use Eloquent relationships to load related data. First, define a relationship in the Tour model:
public function location()
{
return $this->belongsTo(Location::class, 'id_location')
}
Then load Tour and get related location:
$tour = Tour::find($req->id);
$relatedLocation = $tour->location;
First thing, if you are using model then using eloquent relationship will be a better idea to deal with the situation like yours. But if you want to join your table then this will be the way:
public function getTourDetail($id)
{
$tour = Tour::where('id',$id)->first();
//I want to take location.city of the location table
$detail = DB::table('location')
->join('tour','tour.id_location','=','location.id')
->select(
'tour.id as id_tour',
'location.image',
'tour.name',
'tour.id_location',
'location.city'
)->get();
return view('page.tour-detail',compact('tour','detail'));
}
Note: if you are getting id from submitted form then replace first portion of the code with:-
public function getTourDetail(Request $request)
{
$tour = Tour::where('id',$request->id)->first();

Laravel trying to check if the user has relationship with post

I have posts and these posts can be saved by users to read later. I created this relation and I can save or delete them easily. The problem is I can't check if the post is saved or not in frontend. Now I wrote some code to handle this but it doesn't seem to work. here is my controller code:
$articleFlag = 1;
$userID = Auth::User()->id;
if (count($bestarticles) > 0) {
foreach ($bestarticles as $bestarticle) {
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle);
if (count($saveddata) > 0) {
$articleFlag = 1;
} else {
$articleFlag = 2;
}
} //foeach endes here
} //first if endes here
and than I pass the $articleFlag to the view than checking it's value with an if
But the problem is, no matter what I do if (count($bestarticles) > 0) returns true and I get value 1 in view.
Does anybody have any idea what I might be missing?
Here is my user controller relationshio:
function savedarticle(){
return $this->belongsToMany('App\User', 'savearticle', 'user_id',
'article_id');
}
and here goes the functions that i use for saving and deleting:
function savethearticle(Article $article){
$this->savedarticle()->syncWithoutDetaching([$article->id]);
}
function removethearticle(Article $article){
$this->savedarticle()->detach([$article->id]);
}
But there is nothing you need to worry about. I'm able to delete and add.
Or is there another way to check for existing relationship in view or a better way to check it in controller and pass into view?
I am using Laravel 5.4.
It looks as though you have a Collection of Article models, and you're trying to determine whether it is related to the User or not.
If that's the case, I would suggest eager loading the User relation when you originally query the Article models. This has the advantage of using one query to load the relationship, rather than one per Article.
$userId = Auth::id();
$articles = Article::with(['savedarticle' => function ($query) use ($userId) {
return $query->where('user_id' => $userId);
}])->get();
With this Collection, because we have loaded specifically the currently authenticated User, you can then proceed knowing that if the savedarticle relation has a count of 1, that the User relation exists.
foreach ($articles as $article) {
if ($article->savedarticle->count()) {
// User has already saved article
} else {
// User has not saved article
}
}
Should you not be passing the id of bestarticle in the Where clause? Also, it requires a ->get() to actually fire the request off to the database and run the query.
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle);
Should be
$saveddata = DB::table('savearticle')->where('user_id', $userID && 'article_id', $bestarticle->id)->get();

How to query related records only using where clause in laravel?

I tried to search students that belong to particular User/School only using the following the query. I have created one-to-many relationship between User and Students.. Everything seems okay but when I try to search students, it gives me list of students that belong to other Users too.
public function searchStudent(Request $request)
{
$q = $request->q;
$grades = Auth::user()->grades;
$searchPupils = Student::where('user_id','=',Auth::user()->id)->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();
if(count($searchPupils) > 0)
{
return view('add-class', compact('grades'))->withDetails($searchPupils)->withQuery($q);
}
else
{
return view ('add-class', compact('grades'))->withMessage('No Details found. Try to search again !');
}
}
I also tried doing
$searchPupils = Auth::user()->students()->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();
Still it searches for the whole Students table . How should it be done?
the problem is in your query where conditions, use advance where clause as below.
$searchPupils =Student::where('user_id','=',Auth::user()->id)
->where(function($query)use($q){
$query->where('name','LIKE','%'.$q.'%')
->orWhere('email','LIKE','%'.$q.'%');
})->get();

How to delete multiple row from DB table by laravel?

I want to delete all comments from comments table.I did that by doing this but this is not the laravel way. Anyone answer the correct steps please .
$comments = Comment::where('post_id',$id)->get();
if(count($comments)>1)
{
$comment_id= [];
foreach ($comments as $i)
{
$comment_id[] = $i->id;
}
for($i=0;$i<count($comments);$i++)
{
Comment::find($comment_id[$i])->delete();
}
}
elseif (count($comments)==1)
{
$comments->delete();
}
Since each Eloquent model serves as a query builder, try this, all in one line:
Comment::where('post_id',$id)->delete();
Tested in tinker, works as expected, returns count of deleted rows.
Documentation: https://laravel.com/docs/5.3/queries#deletes
You can try the following approach:
public function deleteAll(Request $request)
{
$ids = $request->ids;
Comment::whereIn('id',explode(",",$ids))->delete();
}
DB::table('users')->whereIn('id', $ids_to_delete)->delete();
or
$org-products()->whereIn('id', $ids)->delete();
Collect only ids from your command like below and destroy by model.
$yourRaws = YourModel::where('name', 'Enver')->get();
...
YourModel::destroy($yourRaws->pluck('id')->toArray());
Enjoy Your Coding !

Categories