Method addSelect does not exist - methods

I'm getting this error message when I try to do a addSelect method in Laravel 5.2
Any ideas?
BadMethodCallException in Macroable.php line 74:
Method addSelect does not exist.
Here is the function in my controller
public function summaryOfMembersTable()
{
$members = MotherProfile::select('last_name')
->orderBy('last_name','ASC')
->distinct()
->get();
$count = $members->count();
$mothers = MotherProfile::select(DB::raw('count(*) as user_count, gender'))
->where('gender', '<>', 'F')
->groupBy('gender')
->get();
$fullnames = $members
->addSelect('first_name')
->orderBy('last_name','ASC')
->distinct()
->get();
$data = [];
$data['members'] = $members;
$data['memberCount'] = $count;
$data['mothers'] = $mothers;
$data['fullnames'] = $fullnames;
return view( 'user/masterlist/summary-of-members', $data);
}
My blade:
Total is {{ $memberCount }}
#foreach ($fullnames as $fullname)
{{ $fullname }}<br>
#endforeach
<hr>
<div class="page-header" style="text-align:center;">
<h3 class="pageHeader">
List of Members
<br>
</h3>
</div>
<div class="row">
<table class="table table-bordered" style="text-align: left;">
<tr>
<th></th>
<th>Full Name (Last, First, Middle)</th>
<th>KLC</th>
<th>Category</th>
<th>Mem Type</th>
<th>Mem Status</th>
<th>Date Baptized</th>
<th>Mother in Spirit</th>
<th>Encoder</th>
</tr>
<tbody>
</tbody>
</table></div>

you are getting a collection instead of an object. addSelect method belong to builder object not to collection. So remove get() from your query and you'll be fine.
$members = MotherProfile::select('last_name')
->orderBy('last_name','ASC')
->distinct()
->get();

$members = MotherProfile::select('id','last_name')
->orderBy('last_name','ASC')
->distinct()
->addSelect(DB::raw("'value' as nameFake"))->get();
before to get()

Related

I get the error of Undefined variable $id even if it is passed

I am using an optional parameter and am encountering the following error:
Undefined variable $id
even if it is passed in the route correctly.
Why am I getting this error? Can you help me please?
Route
Route::get('/project/index/{id?}', [ProjectController::class, 'index'])->name('project.index');
ProjectController
public function index($id=null)
{
if($id){
$projects = Project::withCount(['tasks'=> function (Builder $query){
$query->where('project_id', $id);
}])->get();
} else {
$projects = Project::withCount('tasks')->get();
}
return view('project.index', compact('projects'));
}
View
<tr>
<th>ID</th>
<th>Name</th>
<th>N. Task</th>
<th>Azione</th>
</tr>
#foreach ($projects as $project)
<tr>
<td>{{ $project->id }}</td>
<td>{{ $project->name }}</td>
<td>{{ $project->tasks_count }}</td>
#endif
</tr>
#endforeach
You need to pass the $id to the withCount method with use()
$projects = Project::withCount(['tasks'=> function (Builder $query) use ($id){
$query->where('project_id', $id);
}])->get();
First learn about route: Routing
Remove ? from route
Route::get('/project/index/{id}', [ProjectController::class, 'index'])->name('project.index');
change ProjectController function parmeter from
public function index($id=null)
to
public function index($id)
Done!!

Laravel search not working. this part does not seem to work "->where('forms.Doc_Desc','LIKE','%'.$query.'%') "

I'm trying to make a search box. Merged 5 tables, works properly in my index.
This is my search function
public function search(Request $request) {
$query = $request['query'];
$Rates = DB::table('rates')
->join('forms', 'forms.id' ,'=', 'rates.FormID')
->join('documents', 'documents.FormID', '=', 'rates.formID')
->join('contractors', 'contractors.user_id', '=', 'rates.contractor_id')
->join('countries', 'countries.ID', '=', 'forms.country')->orwhere('documents.Status', '=', '2')->orwhere('documents.Status', '=', '4')->where('forms.Doc_Desc','LIKE','%'.$query.'%')
->get(['rates.Class', 'rates.Rate', 'rates.Rate2','forms.Doc_Desc','documents.FileName', 'documents.Status', 'countries.country', 'contractors.contractor_name'])->groupBy('Doc_Desc')->map(function ($Rate, $key) { return $Rate;});
if (count($Rates) > 0) {
return view('admin.rates',[
'Rates' => $Rates,
]);
}
else {
return back()->withInput()->with('status','No Luck');
}
}
This is my View
#foreach( $Rates as $Rate=>$ID)
<tr>
<td>
#foreach($ID as $IDs)
{{$IDs->contractor_name }}
#break
#endforeach
</td>
<td> {{ $Rate}} </td>
<td>
#foreach($ID as $IDs)
#if ($IDs->Class == 'Metro')
{{$IDs->Rate }} + {{$IDs->Rate2 }}
<small class="text-warning">*</small>
#break
#endif
#endforeach
</td>
<td>
#foreach($ID as $IDs)
#if ($IDs->Class == 'Regional') {{$IDs->Rate }} + {{$IDs->Rate2 }}<small class="text-warning">*</small>
#break
#endif
#endforeach
</td>
<td>
#foreach($ID as $IDs)
#if ($IDs->Class == 'Remote') {{$IDs->Rate }} + {{$IDs->Rate2 }}<small class="text-warning">*</small>
#break
#endif
#endforeach
</td>
<td>
#foreach($ID as $IDs)
#if ($IDs->Class != 'Metro' && $IDs->Class != 'Regional' && $IDs->Class != 'Remote') <span class="badge badge-secondary"> {{$IDs->Class }} </span>
#endif
#endforeach
</td>
I have two different routes created(one for the plain view and another for the search(with different URIs)
it's really messy. im new and hoping someone can help. Thank You!
also added this above my table #if(isset($Rates))
The problem is in the way you are using your where and orwhere clauses:
->orwhere('documents.Status', '=', '2')
->orwhere('documents.Status', '=', '4')
->where('forms.Doc_Desc','LIKE','%'.$query.'%')
If one of those is true it will return you the result without filtering it, so for example if your status is 2 then no matter your $query variable, the result will be returned.
What you need to do is you have to encapsulate the 2 orwhere clauses into one where clause and let the filtering where stand alone or for your example simply use whereIn.
For example:
->where('forms.Doc_Desc','LIKE','%'.$query.'%')
->where(function ($q) {
$q->where('documents.Status', '=', '2')
->orwhere('documents.Status', '=', '4')
})
Or even simpler which will work for your code
->whereIn('documents.Status',[2,4])
->where('forms.Doc_Desc','LIKE','%'.$query.'%')

Laravel soft delete: model::onlyTrashed() returns all

When I try to view only soft deleted records in Laravel the onlyTrashed returns all records.
As you will see I also have a searchform which complifies things a bit. And I think the searchform is the reason this doesn't work but I don't understand why excactly.
Controller:
public function toTrashbin(Request $request) {
$search = '%' . $request->input('search') . '%';
$students = Student::onlyTrashed()
->where('first_name', 'like', $search)
->orWhere('last_name', 'like', $search)
->orWhere('rnumber', 'like', $search)
->paginate(15)
->appends(['search'=> $request->input('search')]);
return view('admin.students.students_trashbin')->with('students', $students);;
}
View:
{{--searchform--}}
<form method="get" action="/students/trashbin" id="searchForm">
<div class="row">
<div class="col-sm-6 mb-2">
<input type="text" class="form-control" name="search" id="search"
value="{{request()->search}}" placeholder="Search by name or R-number">
</div>
<div class="col-sm-2 mb-2">
<button type="submit" class="btn btn-success btn-block">Search</button>
</div>
</div>
</form>
<hr>
#if (count($students) > 0)
{{--table--}}
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">R-number</th>
<th scope="col">Deleted at</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
#foreach ($students as $student)
<tr>
<td>{{$student->first_name}} {{$student->last_name}}</td>
<td>{{$student->rnumber}}</td>
<td>{{$student->deleted_at}}</td>
<td>
restore
</td>
</tr>
#endforeach
</tbody>
</table>
{{$students->links()}} {{--pagination--}}
#else
<p>No students found using your searchquery.</p>
#endif
Somehow the view displays all students, both soft deleted and not soft deleted ones.
However: It works perfectly if I remove the 3 "where"s in the controller. But then I can't use search obviously. Does anyone know how I can make this work with search?
Thanks.
Fixed it by changing the controller to this:
public function toTrashbin(Request $request) {
$search = '%' . $request->input('search') . '%';
$conditions = [
['first_name', 'like', $search, 'or'],
['last_name', 'like', $search, 'or'],
['rnumber', 'like', $search, 'or'],
];
$students = Student::onlyTrashed()
->where($conditions)
->paginate(15)
->appends(['search'=> $request->input('search')]);
return view('admin.students.students_trashbin')->with('students', $students);;
}
Honestly still not sure what was wrong with my original controller so if anyone knows the cause, please let me know. But hey, at least I got it to work.
On your first try, Laravel did something like this:
select * from `students` where `students`.`deletedAt` is not null and `last_name` like 'test' or `last_name` like 'test';
On your second approach, the query was mounted like this:
select * from `students` where `students`.`deletedAt` is not null and (`last_name` like 'test' or `last_name` like 'test');
Be extra careful when using "OR" on SQL because it can mess up your results and "ignore" some conditions.
You can control your parentheses doing somethin like this:
$search = '%' . $request->input('search') . '%';
$query = Student::onlyTrashed();
$query->where('votes', '>', 100)
->orWhere(function($query) use ($search) {
$query->where('name', $search)
->where('votes', '>', 50);
});
$query->paginate(15);
Extra information on Closures here: https://laravel.com/docs/7.x/queries#where-clauses
Have a good day!

Want to Join three table but not work [Eloquent]

I want to
SELECT events.id = scan.event_id IF Scan.student_id MATCH user.student_id SHOW events.id and events.name
But my code dint work, it blank screen nothing happen to show
so blind :|
Controller
public function pdftranscript($id)
{
$users = DB::table('users')
->join('scan', 'users.student_id', '=', 'scan.student_id')
->join('events', 'scan.event_id', '=', 'events.id')
->select('users.*', 'events.m_event_name', 'scan.event_id')
->get();
This blade
#foreach($user as $user)
<tr>
<td>{{$user->student_id}}</td>
<td>{{$user->name}}</td>
#foreach($event as $event)
<td>{{$event->m_event_name}}</td>
#endforeach
<tr>
#endforeach
First you could dd($users) in your controller to check whether you have got a successful query. Then in blade, it should be:
#foreach($users as $user)
<tr>
<td>{{$user->student_id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->m_event_name}}</td>
<tr>
#endforeach
You already took the values in $users variable..No need for the second foreach loop.
#foreach($users as $user)
<tr>
<td>{{$user->student_id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->event_id}}</td>
<td>{{$user->m_event_name}}</td>
<tr>
#endforeach

Laravel - Undefined property: Illuminate\Database\MySqlConnection::$username

I wrote a query to pass parameter from view to controller, and I got this error:
Undefined property: Illuminate\Database\MySqlConnection::$username
View Passing the parameter
<td width="25%"><a class="btn btn-info" href="{{ route('gamesListDetail',$game->id) }}">{{ $game->name }}</a></td>
Receiving Controller
public function gamesListDetail($id = null)
{
$gamelists = DB::table("platform_games")
->select("platform_games.id", "platform_games.username","game_player.game_id")
->join("game_player","game_player.game_id","=","platform_games.id")
->where('platform_games.id',$id)
->take(5);
return view('soccerrave.games.gamesListDetail', compact('gamelists'));
}
Receiving View
<tbody>
#foreach($gamelists as $key => $gamelist)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $gamelist->username }}</td>
</tr>
#endforeach
<tr>
<td colspan="8">
{{ $gamelists->links() }}
</td>
</tr>
</tbody>
I expect the view to display top 5 data based on the parameter. But I got this error:
Undefined property: Illuminate\Database\MySqlConnection::$username
Documentation says:
skip / take
To limit the number of results returned from the query, or to skip a
given number of results in the query, you may use the skip and take
methods:
$users = DB::table('users')->skip(10)->take(5)->get();
So by example we see that after take method there must be get() call.
So fix Your code:
public function gamesListDetail($id = null)
{
$gamelists = DB::table("platform_games")
->select(
"platform_games.id",
"platform_games.username",
"game_player.game_id"
)
->join(
"game_player",
"game_player.game_id", "=", "platform_games.id"
)
->where('platform_games.id', $id)
->take(5)
->get(); // this one is required
return view('soccerrave.games.gamesListDetail', compact('gamelists'));
}

Resources