Pass variable data between methods in same controller laravel 5.6 - php

Hey guys how do u pass a variable between a function within the same controller? I have tried making a global variable and using Session:: to set and get the values but neither of the method works. I am getting the values of the start_date and end_date from my generate.blade.php and pass the value to my downloadPDF function to filter the data based on the date range. Anyone able to enlighten me how can i accomplish this?
GenerateReportController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Attendance;
use App\Subject;
use PDF;
use Session;
use View;
class GenerateReportController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public $start_date;
public $end_date;
public function index()
{
$this->start_date = Input::get('startDate');
$this->end_date = Input::get('endDate');
$subjects = Subject::all();
return View::make('generate', compact('subjects',$subjects));
}
public function downloadPDF()
{
$dateBetween = Attendance::whereBetween('date',array($this->start_date, $this->end_date))->get();
//dd($dateBetween);
$pdf = PDF::loadView('pdf',compact('dateBetween'));
$name = "Attendance Report";
return $pdf->stream($name.'.pdf');
}
}
generate.blade.php
#extends('master')
#section('page_header')
<div class="container-fluid">
<h1 class="page-title">Attendance Records</h1>
<a href="/dashboard/attendance/report/" target="_blank" class="btn btn-primary">
<i class="voyager-list" style="font-size:15px;"></i>
<span>Generate Report</span>
</a>
</div>
#endsection
#section('content')
<div class="page-content browse container-fluid">
<div class="row">
<div class="col-md-12">
<div class="panel panel-bordered">
<div class="panel-body">
{!! Form::Label('subject', 'Subject:') !!}
<select class="form-control" name="s_name">
#foreach($subjects as $subject)
<option value="{{$subject->s_name}}">{{$subject->s_name}}</option>
#endforeach
</select>
<br>
{!! Form::Label('startDate', 'Start Date:') !!}<br>
{!! Form::input('date', 'startDate', null,['id' => 'datetimepicker','class' => 'datepicker', 'data-date-format' => 'yy/mm/dd']) !!}
<br>
<br>
{!! Form::Label('endDate', 'End Date:') !!}<br>
{!! Form::input('date', 'endDate', null, ['id' => 'datetimepicker','class' => 'datepicker', 'data-date-format' => 'yy/mm/dd']) !!}
</div>
</div>
</div>
</div>
</div>
#endsection
web.php
Route::get('dashboard/attendance/generate','GenerateReportController#index');
Route::get('dashboard/attendance/report','GenerateReportController#downloadPDF');

SOLVED
Instead of passing the variable one a function to another. Use a post method to send the $request to the second controller and use $request->name to get the value.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Attendance;
use App\Subject;
use Session;
use PDF;
use View;
class GenerateReportController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$subjects = Subject::all();
return View::make('generate', compact('subjects'));
}
public function downloadPDF(Request $request)
{
$dateBetween = Attendance::whereBetween('date',array($request->startDate,$request->endDate))->where('s_code',$request->id)->get();
$pdf = PDF::loadView('pdf',compact('dateBetween'));
$name = "Attendance Report";
return $pdf->stream($name.'.pdf');
}
Blade View
{!! Form::open(['action'=>'GenerateReportController#downloadPDF','target' => '_blank']) !!}
{!! Form::Label('subject', 'Subject:') !!}
<select class="form-control" name="id">
#foreach($subjects as $subject)
<option value="{{$subject->id}}">{{$subject->s_name}}</option>
#endforeach
</select>
<br>
{!! Form::Label('startDate', 'Start Date:') !!}<br>
{!! Form::date('startDate', 'startDate',['id' => 'datetimepicker','class' => 'datepicker']) !!}
<br>
<br>
{!! Form::Label('endDate', 'End Date:') !!}<br>
{!! Form::date('endDate', 'endDate',['id' => 'datetimepicker','class' => 'datepicker']) !!}
<br>
<br>
{!!Form::submit('Generate PDF',['class' => 'btn btn-primary'])!!}
{!! Form::close() !!}
web.php
Route::get('dashboard/attendance/generate','GenerateReportController#index');
Route::post('dashboard/attendance/report','GenerateReportController#downloadPDF');

Try like below
In Route
Route::get('dashboard/attendance/report','GenerateReportController#downloadPDF');
First add this facade in your controller
use Illuminate\Http\Request;
After convert your function to
public function downloadPDF($request)
{
//try to print first dd($request->all())
$dateBetween = Attendance::whereBetween('date',array($request->start_date, $request->end_date))->get();
//dd($dateBetween);
$pdf = PDF::loadView('pdf',compact('dateBetween'));
$name = "Attendance Report";
return $pdf->stream($name.'.pdf');
}
Form
{!! Form::open(['action'=>'GenerateReportController#downloadPDF']) !!}
{!! Form::Label('subject', 'Subject:') !!}
<select class="form-control" name="s_name">
#foreach($subjects as $subject)
<option value="{{$subject->s_name}}">{{$subject->s_name}}</option>
#endforeach
</select>
<br>
{!! Form::Label('startDate', 'Start Date:') !!}<br>
{!! Form::input('date', 'startDate', null,['id' => 'datetimepicker','class' => 'datepicker', 'data-date-format' => 'yy/mm/dd']) !!}
<br>
<br>
{!! Form::Label('endDate', 'End Date:') !!}<br>
{!! Form::input('date', 'endDate', null, ['id' => 'datetimepicker','class' => 'datepicker', 'data-date-format' => 'yy/mm/dd']) !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}

Related

only show future appointments PHP

I am trying to learn PHP by myself so i decided to create a little health appointment manager.
I tried to do a filter in the Controller so it only shows the future appointments in the index view but I can not find the right way to do it:
HereĀ“s is what I wrote down in my Controller and my view:
Controller:
{
$citas = Cita::all();
$fecha_hora = get('fecha_hora');
if($fecha_hora>date_default_timezone_get()){
return view('citas/index',['citas'=>$citas]);
}
}
and my index view:
#include('flash::message')
{!! Form::open(['route' => 'citas.create', 'method' => 'get']) !!}
{!! Form::submit('Crear cita', ['class'=> 'btn btn-primary'])!!}
{!! Form::close() !!}
{!! Form::open(['route' => 'citas.index', 'method'=>'get']) !!}
<div class="form-group">
<br>
{!! Form::submit('Citas pasadas',['class'=>'btn btn-default btn-sm']) !!}
{!! Form::close() !!}
{!! Form::open(['route' => 'citas.index', 'method' => 'get']) !!}
{!! Form::submit('Todas las citas', ['class'=> 'btn btn-link btn-sm pull-right'])!!}
{!! Form::close() !!}
<br><br>
What i want is to only show the future appointments in the main view but also have a tab "Citas pasadas" (Past appointments in english) where i can see only past appointments.
Maybe you can prepare scopes in your Modelfile. Something like this.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Cita extends Model
{
public function scopeUpcoming($query) {
return $query->where('start_time', '>', date('Y-m-d H:m:s'))->orderBy('start_time', 'desc');
}
public function scopePrevious($query) {
return $query->where('start_time', '<', date('Y-m-d H:m:s'))->orderBy('start_time', 'desc');
}
}
Then, access them like Cita::upcoming() or Cita::previous()

(1/1) ReflectionException Error Class App\Http\Request\UpdateApplicantRequest does not exist

I am new to laravel and I am trying to update to profile of the user who logged in. The error says:
Class App\Http\Request\UpdateApplicantRequest does not exist
But I imported it in the top of my controller.
HomeController.php
<?php
namespace App\Http\Controllers\Applicant;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\ApplicantsRepository;
use Flash;
use Response;
use App\Models\Applicant;
use App\Http\Request\UpdateApplicantRequest;
class HomeController extends Controller
{
private $applicantRepository;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(ApplicantsRepository $applicantRepo)
{
$this->middleware('applicant');
$this->applicantsRepository = $applicantRepo;
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('applicant-dashboard.home');
}
public function edit($id)
{
//$applicant = $this->applicantRepository->findWithoutFail($id);
$applicant = Applicant::where('id',$id)->get()->last();
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicant', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.home'));
}
$input = $request->all();
$applicant = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.home'));
}
}
Here is the code in my routes:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
Route::patch('/put', 'HomeController#update')->name('applicant.update');
and the code in my blade file:
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
I am looking for help.
Thanks in Advance.
Firstly, you use wrong namespace of UpdateApplicantRequest.
Change:
use App\Http\Request\UpdateApplicantRequest;
To:
use App\Http\Requests\UpdateApplicantRequest;
Then, change your form from:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
to:
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'post']) !!}
{!! method_field('patch') !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}

Laravel Not posting to database

There is a bug in the code somewhere and I cant seem to find it , any help would be great. Its a simple form that stores to a DB.
The app is using laravel 5.2 and all that is needed is to collect data. when the submit button is hit on the form nothing!
route
Route::resource('/form' , 'PagesController');
controller only needs to indes, create and store , thats all the app needs to do.
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use Data;
use App\Http\Requests\DataRequest;
use Carbon\Carbon;
class PagesController extends Controller
{
//Display Index
public function index()
{
return view ('welcome');
}
public function create()
{
return view ('create');
}
//Store Articles from form
public function store(DataRequest $request)
{
Data::create($request->all());
return redirect('create')->with('message' , 'Form submitted');
}
}
model uses a simple protected fields list and carbon to store timestamps
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Requests\DataRequest;
use Carbon\Carbon;
class Data extends Model
{
protected $fillable = [
'name',
'email',
'phone',
'company',
'addcomments',
'published_at',
];
protected $dates = ['published_at'];
//Get all published articles by date
public function scopePublished($query)
{
$query->where('published_at' , '<=' , Carbon::now());
}
//Get all unpublished or future articles
public function scopeUnpublished($query)
{
$query->where('published_at' , '>=' , Carbon::now());
}
// Set form to publish articles with a time and date in the Published_at field
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d' , $date);
}
}
form
{!! Form::open(['url' => 'form']) !!}
<div class="form-group">
{!! Form::label('name' , 'Name:') !!}
{!! Form::text('name', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email' , 'EMail:') !!}
{!! Form::text('email', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('phone' , 'Phone Number:') !!}
{!! Form::text('phone', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('company' , 'Company:') !!}
{!! Form::text('company', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('addcomments' , 'Additional Comments:') !!}
{!! Form::textarea('addcomments', null , ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Submit Now', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
So the issue was what was mentioned in the comments
use DATA;
to
use App\DATA;
and a mixture of a few little front end tweaks
all sorted

Laravel form error message

I created a form for myself and it was working perfect. I did some rules like: if the user haven't wrote anything in the form or haven't wrote enough, give me some error message. This was working while used the 'former' package instead of the normally used 'form' package. Now I changed my form from "Former" to "Form" and now my error message are gone.. Well my form works and the rules too. If I don't write anything in my form or not at least 3 characters in the title/content section, it should redirect me with the errors I need. This works, but without the error message.
Here is my form:
#extends('master')
#section('content')
{!! Form::open(array('action' => 'Test\\TestController#store')) !!}
<div class="form-group">
{!! Form::label('thread', 'Title:') !!}
{!! Form::text('thread', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('content', 'Body:') !!}
{!! Form::textarea('content', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Add Thread', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
My Controller#store function:
public function store(StoreRequest $request){
Thread::create($request->all());
return redirect(action('Test\\TestController#index'));
}
my Model:
<?php
namespace App\Models\Thread;
use Illuminate\Database\Eloquent\Model;
class Thread extends Model {
public $table = 'thread';
public $fillable = [
'thread',
'content',
];
}
and now the rules ( StoreRequest.php ) :
<?php
namespace App\Http\Requests\Store;
use App\Http\Requests\Request;
class StoreRequest extends Request {
public function rules() {
return [
'thread' => 'required|min:3',
'content' => 'required|min:3'
];
}
public function authorize() {
return true;
}
}
The error message was getting automaticly generated. Laravel did that for me. But not anymore.
Does anybody see why?
You can check if the form returned any error with something along these line:
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
Or you could use BootForm and let it handle everything for you

Products list not seen while editing, using form model binding in laravel 5.1

In my ecommerce project, I have Product and Carousel Model.
Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = [
'code', 'name', 'description', 'special_note', 'sort', 'display', 'weight', 'enquiry'
];
public function carousels()
{
return $this->belongsToMany('App\Carousel')->withTimestamps();
}
}
Carousel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Carousel extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $fillable = ['name', 'display', 'sort'];
public function products()
{
return $this->belongsToMany('App\Product')->withTimestamps();
}
public function getProductListAttribute()
{
return $this->products->lists('id');
}
}
Here's the controller:
public function create()
{
$products = Product::lists('name', 'id');
return view('admin.carousels.create', compact('products'));
}
public function store(Request $request)
{
$carousel = Carousel::create($request->all());
$carousel->products()->attach($request->input('product_list'));
return redirect()->back();
}
public function edit($id)
{
$carousel = Carousel::findOrFail($id);
$products = Product::lists('name', 'id');
return view('admin.carousels.edit', compact('carousel', 'products'));
}
public function update(Request $request)
{
dd($request->all());
}
The carousel form:
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control input-sm', 'id' => 'name']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('sort', 'Sort:') !!}
{!! Form::text('sort', null, ['class' => 'form-control input-sm', 'id' => 'sort']) !!}
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
{!! Form::label('display', 'Display:') !!}
{!! Form::select('display', ['Disabled' => 'Disabled', 'Enabled' => 'Enabled'], null, ['class' => 'form-control input-sm', 'id' => 'display']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::label('product_list', 'Products:') !!}
{!! Form::select('product_list[]', $products, null, ['class' => 'form-control input-sm', 'multiple']) !!}
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group">
{!! Form::submit($submitButtonText, ['class' => 'btn btn-primary btn-block m_top_15', 'id' => $submitButtonId]) !!}
</div>
</div>
Now, the problem is that, when I use form model binding to edit the carousel form, I get no product displayed in the select box, though I can see all the products to select from. The selected products are not seen for the particular carousel.
What is the mistake that I have made ? Kindly help me out.
Thanks.
P.S: I am using Laravel 5.1 and came across this issue for the first time. Earlier I used to do this in Laravel 5 without any issue.
This may be related to how lists() is handled in 5.1. From the upgrade guide -
The lists Method
The lists method now returns a Collection instance instead of a plain
array for Eloquent queries. If you would like to convert the
Collection into a plain array, use the all method:
User::lists('id')->all(); Be aware that the Query Builder lists method
still returns an array.

Categories