I'm stuck with the next topic. Help would be very appreciated.
Want to make a simple call to a view but, it becomes null during the process. Originally I was not making filters, just showing everything (notes:all()). Right now I'm trying to filter by date, ID, or user name, that's what I capture on my left controls before search button (bottom) is clicked. But now with filters applied (notas -sales-), it becomes null...
I post you my code, so you'll be kind and help me to identify why. I suspect about the routes (it's the fisrt time I define them manually).
The routes
Route::get('notas/notasGet/', 'NotasController#notasGet')->name('notas.notasGet');
Route::post('notas/notasPost/', 'NotasController#notasPost')->name('notas.notasPost');
Route::get('notas/create/', 'NotasController#create')->name('notas.create');
Route::get('notas/store/', 'NotasController#store')->name('notas.store');
Route::put('notas/update/{id}', 'NotasController#update')->name('notas.update');
Route::get('notas/{id}/edit', 'NotasController#edit')->name('notas.edit');
Route::delete('notas/destroy/{id}', 'NotasController#destroy')->name('notas.destroy');
Route::post('notas/cajaAbrir/', 'NotasController#cajaAbrir')->name('notas.cajaAbrir');
Route::post('notas/cajaCortar/', 'NotasController#cajaCortar')->name('notas.cajaCortar');
The ones with problem are notasGet, notasPost, which I call first from index
I call them from app.blade.php
<nav class="navbar navbar-expand-md navbar-light navbar-laravel">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/registroaccesos/destinationSearchGet/">Acceso</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/gymmgr/public/notas/notasGet/">Venta</a>
</li>
At my controller, dd($notas); works fine
public function notasGet()
{
$fechaInicio = null;
$fechaFin = null;
$headData = array('pageTitle' => 'Admin Home - View all destinations');
$currentDate = Carbon::now()->format('Y-m-d');
//$notas = Nota::whereRaw('dtmHoraCargo IS NULL')->get()->first();
$notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get();
//dd($notas);
$users = null;
$users = User::all();
$cajaAbierta = Caja::whereRaw('dtmCorte IS NULL')->get()->first();
//dd($cajaAbierta);
$data = array('notas'=>$notas,'fechaInicio'=>$fechaInicio,'fechaFin'=>$fechaFin, 'users'=>$users, 'caja'=>$cajaAbierta);
return view('notas.index', $data);
}
public function notasPost(Request $request)
{
$strSearch = $request->input('strSearch');
$fechaInicio = $request->input('fechaInicio');
$fechaFin = $request->input('fechaFin');
$strPatron = $request->input('strPatron');
$notas = null;
switch ($strSearch) {
case 0:
$notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get();
break;
case 1:
$notas = Nota::whereRaw("dtmHoraCargo >= ? AND dtmHoraCargo <= ?", array($fechaInicio." 00:00:00", $fechaFin." 23:59:59"))->get();
break;
case 2:
$notas = Nota::find($strPatron);
break;
case 3:
$notas = Nota::whereDate('dtmHoraCargo', '=', Carbon::today()->toDateString())->get();
break;
}
$users = null;
$users = User::all();
$cajaAbierta = Caja::whereRaw('dtmCorte IS NULL')->get()->first();
// dd($cajaAbierta);
$data = array('notas'=>$notas,'fechaInicio'=>$fechaInicio,'fechaFin'=>$fechaFin, 'users'=>$users, 'caja'=>$cajaAbierta);
dd($notas);
/*It echoes the right nota but suddenly and going to the view it's null and the view calling crashes.
Nothing happens in between, so I don't know*/
return view('notas.index', $data);
//return view('registroaccesos.index', ['headData'=>$headData, 'usuarioSearch'=>$usuarioSearch]);
}
At index
<table class="table">
<thead class="thead-light">
<tr>
<th>Folio</th>
<th>Fecha y hora</th>
<th>Total</th>
<th>Aplica a</th>
<th>Saldo</th>
</tr>
</thead>
<tbody>
#foreach($notas as $nota)
<tr>
<td> {{ $nota->idNota }} ></td>
<td> {{ $nota->dtmHoraCargo }} </td>
<td> {{ $nota->dcmTotal }} </td>
<td> {{ empty($nota->idAplicaA)? '' : $nota->aplicaa->strPaterno . ' ' . $nota->aplicaa->strMaterno . ' ' . $nota->aplicaa->strNombre }} </td>
<td> {{ $nota->dcmSaldo }} </td>
</tr>
#endforeach
</tbody>
</table>
</main>
</div>
</div>
it triggers exception (notas is null, why????)
Trying to get property 'idNota' of non-object (View: C:\xampp\htdocs\gymmgr\resources\views\notas\index.blade.php)
In your switch in case 2 you get single object, in another cases you get collection. So, seems exception happen in this case 2.
case 2:
$notas = Nota::find($strPatron); // Will return object, but not the collection.
break;
You can try this:
case 2:
$notas = collect(Nota::find($strPatron));
break;
Related
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.'%')
I am trying to store view foreach value in database using controller Is there any other way to store value by controller without view foreach
View
#foreach ($ticket_details as $key=>$ticket_detailss)
<li>
<h3 style="text-align:center ">TICKET ID<small class="text-success "><br type="text" id="ticket_id" name="ticket_id" >{{$ticket_detailss->ticket_id }}</small></h3>
</li>
<li>
<h3 style="text-align:center ">SUBJECT<small class="text-success "><br>{{$ticket_detailss->subject }}</small></h3>
</li>
<li>
<h3 style="text-align:center ">NAME<small class="text-success "><br type="text" id="names" name="names" >{{$ticket_detailss->name }}</small></h3>
</li>
<li>
<h3 style="text-align:center ">ID<small class="text-success "><br type="text" id="user_filter_id" name="user_filter_id" >{{$ticket_detailss->user_filter_id }}</small></h3>
</li>
<li>
<h3 style="text-align:center ">STAFF ID<small class="text-success "><br type="text" id="user_staff_id" name="user_staff_id" >{{$ticket_detailss->user_staff_id }}</small></h3>
</li>
#endforeach
Controller
public function manager_send_messageChat(Request $request)
{
$this - >validate($request, [
'message' = >'required|string|max:255', 'ticket_id' = >'string|max:255',
]);
foreach($ticket_details as $ticket_detailss) {
$ticket_detailss['name'] = $ticket_detailss - >name;
$ticket_detailss['user_filter_id'] = $ticket_detailss - >user_filter_id;
$ticket_detailss['user_staff_id'] = $ticket_detailss - >user_staff_id;
$input['message'] = $request - >message;
$input['manager_staff_id'] = Auth::user() - >staff_id;
$input['manager_filter_id'] = Auth::user() - >id;
$input['manager_name'] = Auth::user() - >name;
$input['reply_by'] = 'staff';
$input['ticket_id'] = $request - >ticket_id;
User_Ticket_Chat::create($input);
return redirect('/ticket') - >with('success', ' THIS TICKET ASSIGNED FOR YOU .');
}
}
try this in your controller and get the record as an array. the scripts will check and insert record into your db before displaying in your view. hope it helps
$data['ticket_details']='assign record'; //this goes to the view
$ticket_details[]='assign record'; this goes to the controller
foreach($ticket_details as $key=>$ticket_detailss)
//checking if exacts record exists
if(DB::table('table')->where('id',$ticket_detailss->ticket_id)->where('subject',$ticket_detailss->subject)->where('name',$ticket_detailss->name)->where('user_filter_id',$ticket_detailss->user_filter_id)->where('user_staff_id',$ticket_detailss->user_staff_id)->first())
{
//if record exists, do not insert
}else{
//if record do not exists, insert into db
$save = DB::table('table')->insert([
'subject' => $ticket_detailss->subjecte,
'name' => $ticket_detailss->name,
'user_filter_id' => $ticket_detailss->user_filter_id,
'user_staff_id'=> $ticket_detailss->user_staff_id,
]);
}
}
return view('blade',$data);
I'm wondering how I can pass a laravel query result back to my ajax function on success. I've read something about json encode but I'm getting kind of confused as how I can do so, not really familiar with json that much.
Ajax
$('#userFilter').change(function(){
var selected = $('#userFilter').find(':selected').val();
var token = $('#token').val();
$.ajax({
type: 'POST',
url: '/admin_panel',
data: {
_token : token,
selected : selected,
},
success: function(data){
$('#usersViewBody').html(data);
}
})
});
Controller
function filterUsers(Request $request) {
$selected = $request->selected;
if ($selected == 0) {
$users = DB::table('users')->paginate(15);
} elseif ($selected == 1){
$users = DB::table('users')
->where('status', '=', '0')
->orWhere('status', '=', '1')
->paginate(15);
} else {
$users = DB::table('users')
->where('status', '=', '2')
->orWhere('status', '=', '3')
->paginate(15);
}
return $users;
View
<tbody id="usersViewBody">
#foreach($users as $user)
<tr>
<td><a data-uid="{{$user->id}}" class="openUserPanel" href="#tabUserInfo"> {{$user->name}}</a></td>
<td>{{$user->department}}</td>
<td>{{$user->position}}</td>
#if($user->status == 0)
<td class="userActive">Active</td>
#elseif($user->status == 1)
<td class="userOOO">On Leave</td>
#elseif($user->status == 2)
<td class="userInactive">Retired</td>
#else
<td class="userInactive">Terminated</td>
#endif
#if($user->status == 2 || $user->status == 3)
<td><button class="btn btn-xs btn-default payrollModalTrigger disabled" data-uid="{{$user->id}}">Update Payroll</button></td>
#else
<td><button class="btn btn-xs btn-default payrollModalTrigger" data-uid="{{$user->id}}">Update Payroll</button></td>
#endif
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="text-center">
{{ $users->links() }}
</div>
Instead of returning collection $users from your controller you need to return view back to the ajax, hence change the return of the controller method from
return $users;
to
return view('name of the view', compact('users'));
Blade is used when the page is first loaded (i.e. it's rendered on the server), it will only run again if you reload the page which is in contrast to what you're trying to do with ajax, i.e. interact with the server without a page reload.
What you want to do in your ajax success call is constrcut HTML for the contents of your table body in javascript along with the data you get in the response from the server.
This package has already done all the heavy lifting for you https://github.com/yajra/laravel-datatables, it would, of course, be good to learn how to do it yourself though!
Let me explain with a couple of word my problem.
On my controller i have this line:
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
This works for existing users, but when i try to create new ones i receive
Call to a member function tasks() on null
Can i with something like this or what do you suggest ?
if(!is_null($tasks))
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
}
This i my show function on controller
public function show(){
$user = Auth::user();
if(!$user)
return redirect('/')->withErrors(config('constants.NA'));
$countries = Country::all()->lists('name', 'id')->toArray();
$profile = $user->profile;
$student = $profile->student;
// Tasks showed on students profile
if ($student->group) {
$tasks = $student->group->tasks()
->orderBy('created_at', 'desc')
->withPivot('id')
->get();
}
// Classmates
if ($student->group) {
$classmates = $student->group->students()
->where('id', '!=', $student->id)
->get();
}
// Activated books
$books = Auth::user()->books()->orderBy('grade_id', 'asc')->get();
if(!is_null($student->group))
$iTasks = $student->group->tasks->count();
else {
$iTasks = 0;
}
$iTodos = $user->todos->count();
return view('student.profile.show',compact('user','profile', 'countries', 'iTasks', 'iTodos', 'tasks', 'classmates', 'books'));
}
This is my show view, for the tasks
<div class="tab-pane <?php if(isset($tab) && $tab == 'timeline'): ?> active <?php endif; ?>" id="timeline">
#if($tasks->count())
<div class="timeline">
#foreach($tasks as $task)
<!-- TIMELINE ITEM -->
<div class="timeline-item">
<div class="timeline-badge">
<div class="timeline-icon">
<i class="mdi mdi-clipboard-text font-red-intense"></i>
</div>
</div>
<div class="timeline-body">
<div class="timeline-body-arrow"> </div>
<div class="timeline-body-head">
<div class="timeline-body-head-caption">
<span class="timeline-body-title font-blue-madison">
{{ $task->professor->profile->user->name }}
</span>
<span class="timeline-body-time font-grey-cascade">ju ca caktuar një detyrë të re.</span>
</div>
</div>
<div class="timeline-body-content">
<span class="font-grey-cascade">
{{ $task->pivot->comment }}
</span>
</div>
<hr>
Lenda: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->subject->name }}</span>
<div class="pull-right">
Krijuar më: <span class="timeline-body-time font-grey-cascade sbold">{{ $task->created_at->format(Config::get('klasaime.date_format')) }}</span>
</div>
</div>
</div>
<!-- END TIMELINE ITEM -->
#endforeach
</div>
#else
<div class="alert">
Ju nuk keni asnje detyrë të caktuar!
</div>
#endif
</div>
Looks to me like you haven't added the student to a group yet, or that somehow hasn't been persisted. If you have added the student to a group after creating and saving the student, try this:
$student->load('group')
Before running:
$tasks = $student->group->tasks()->orderBy('created_at', 'desc')->withPivot('id')->get();
I'll need to see more of your code to give a more accurate answer. But the error you're getting is related to the ->group, of your student, not your student itself.
Do a simple check to see if the group exists and then carry on with whatever action you need to perform.
// controller
$tasks = null;
if ($student->group) {
$tasks = $student->group->tasks()
->orderBy('created_at', 'desc')
->withPivot('id')
->get();
}
// view
#if($tasks)
{{ $tasks->id }}
#else
No tasks found
#endif
Edit : In your controller add $tasks = null; and $classmates = null; at top. And in your view change #if($tasks->count()) to #if($tasks). I'm not sure where your use the classmates variable, but add a check to see if it's null before you use it.
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()