I am coding in Laravel, How can I pass variable to one function to another function in Controller,
In controller file I have 2 functions like this
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
$interview = $request->get('interview');
$assignto = $request->get('assignto');
$dateTime = $request->get('dateTime');
$note = $request->get('note');
$interviewDetails = ([
'interview' => $interview,
'assign_to' => $assignto,
'date_time' => $dateTime,
'note' => $note,
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $candidateName], function ($message) use ($assignto, $name) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$name);
});
return redirect('list-candidate');
}
I want to use $candidateName and $name in assignInterview() function from hiringEmployee() function.
How can I do it?
You won't be able to use the $name and $candidateName directly from the other function as they look like they are for two different requests, however, it looks like you're saving that data to database when you're creating a new EmployeeHire in your hiringEmployee() method so you should already have access to that information in your assignInterview() method:
$assignInterview = EmployeeHire::find($id); // this is where you loading the model
$candidateName = $assignInterview->candidateName;
$name = $assignInterview->file;
In your situation , you can use two approach:
#1
Use Session Variable as below:
Session::put('candidateName', $candidateName);
Then:
$value = Session::get('candidateName');
#2
Use class attribute:
class acontroller extends Controller
{
private $classCandidateName;
}
You can try something like this:
public function hiringEmployee(Request $request)
{
$hireEmployee = new EmployeeHire();
$hireEmployee->candidateName = $request->get('candidateName');
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/cv', $name);
$hireEmployee->file = $name;
$hireEmployee->save();
return redirect('list-candidate');
}
public function assignInterview(Request $request, $id)
{
$assignInterview = EmployeeHire::find($id);
if(is_null($assignInterview)){
return redirect()->back()->withErrors(['Error message here']);
}
$interviewDetails = ([
'interview' => $request->get('interview'),
'assign_to' => $request->get('assignto'),
'date_time' => $request->get('dateTime'),
'note' => $request->get('note'),
]);
$assignInterview->interview_details = $interviewDetails;
$assignInterview->save();
Mail::send('emails.hireemployee', ['candidateName' => $assignInterview->candidateName], function ($message) use ($assignto, $assignInterview->file) {
$message->subject('Interview For New Candidate!');
$message->from('hrm#wcg.com', 'HRM');
$message->to($mail);
$message->attach('uploads/cv/'.$assignInterview->file);
});
return redirect('list-candidate');
}
Please, you should to be careful with find($id). If it is a null, you will get an error.
Have fun!
Related
I have functions that I use in my Article model, they add likes to cookies for a specific article and record the time
public static function hasLikedToday($articleId, string $type)
{
$articleLikesJson = \Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
// Check if there are any likes for this article
if (! array_key_exists($articleId, $articleLikes)) {
return false;
}
// Check if there are any likes with the given type
if (! array_key_exists($type, $articleLikes[$articleId])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$articleId][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public static function setLikeCookie($articleId, string $type)
{
// Initialize the cookie default
$articleLikesJson = \Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
// Update the selected articles type
$articleLikes[$articleId][$type] = today()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
The php.blade page itself has buttons
Like Heart
Like Finger
Here are the routes web.php
Route::get('/article', function () {
$articleLikesJson = \Cookie::get('article_likes', '{}');
return view('article')->with([
'articleLikesJson' => $articleLikesJson,
]);
});
Route::get('article/{id}/like', 'App\Http\Controllers\ArticleController#postLike');
And the postLike() function itself in the controller
public function postLike($id) {
$article = Article::find($id);
$like = request('like');
if ($article->hasLikedToday($article->id, $like)) {
return response()
->json([
'message' => 'You have already liked the Article #'.$article->id.' with '.$like.'.',
]);
}
$cookie = $article->setLikeCookie($article->id, $like);
$article->increment('like_{$like}');
return response()
->json([
'message' => 'Liked the Article #'.$article->id.' with '.$like.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
In general, what is the problem, I have 2 types of likes that can be seen in php.blade, and the problem is to pass the choice of the type of like to the postLike() function, if in my function instead of $like I write 'heart', then everything will be work, but I need to determine which type we choose (heart or finger), tell me how this can be done?
You can use Laravel's Request object.
https://laravel.com/docs/8.x/requests#input
Like this:
use Illuminate\Http\Request;
public function postLike($id, Request $request)
{
$type = $request->input('type');
}
public function getleaveType(Request $request){
$leave_types = leaveType::all();
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
return redirect('leave/leaveType', ['leave_t' => $leave_types]);
}
Looks like you are passing data $leave_types to route and not to view.
It should be something like this
return view('view_name', ['leave_t' => $leave_types]);
OR
return view('view_name')->with('leave_t',$leave_types);
Edit:
Try this
public function getleaveType(Request $request){
//create leave-type
if($request->isMethod('POST')){
$leave_Type = new leaveType;
$leave_Type->leave_type = $request->input('leaveType');
$leave_Type->staff_type = $request->input('staffType');
$leave_Type->leave_days = $request->input('leaveDays');
$leave_Type->leave_description = $request->input('leaveDescription');
$leave_Type->save();
}
$leave_types = leaveType::all();
return view('view_name')->with('leave_t',$leave_types);
}
return redirect()->route('leave/leaveType')->with( ['leave_t' => $leave_types]);
Try to use redirect like above and encapsulate the values you want to pass using with function
I have 'sendsms' function which i used it in one of my controllers and worked fine. now what i need to know how i can make class reference of this code to use it in other controllers, instead of copy/paste whole code in all controllers.
In other Q/A they mentioned about only creating reference but i wanted to do it properly like using constructor or etc, not just doing things work, i want to do it like real-world project.
Here's the code in controller :
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|string|min:6',
'gametype' => 'required|string|min:3',
'description' => 'required|string|min:1|max:180',
'price' => 'required|numeric|min:4',
'buyyer_id' => 'required|numeric|min:1'
// 'seller_id' => 'required|numeric|min:1'
]);
// return RequestModel::create([
// 'title' => $request['title'],
// 'description' => $request['description'],
// 'gametype' => $request['gametype'],
// 'price' => $request['price'],
// 'buyyer_id' => $request['buyyer_id'],
// 'seller_id' => Auth::user()->id,
// ]);
//
$requestModel = new RequestModel;
// store
$requestModel->title = $request['title'];
$requestModel->description = $request['description'];
$requestModel->gametype = $request['gametype'];
$requestModel->price = $request['price'];
$requestModel->buyyer_id = $request['buyyer_id'];
$requestModel->seller_id = Auth::user()->id;
$requestModel->save();
return $this->sendSms($request['title'], $request['gametype']);
}
// I want to use this code in another class to use it in all controllers without copy/paste it.
function sendSms($reqid, $recgametype) {
//Send sms to getway
//implement later.
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$reqid. " ) for ( " .$recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
$client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
echo $ex->faultstring;
}
}
I'm right now learning and I'm beginner at this so help to understand how to make it work properly. Thanks.
You can create a separate SMS class like :
<?php
namespace App;
class SMS {
private $reqid;
private $recgametype;
public function __construct($reqid, $recgametype)
{
$this->reqid = $reqid;
$this->recgametype = $recgametype;
}
public function send()
{
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$this->reqid. " ) for ( " .$this->recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
return $client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
throw new \Exception('SMS sending failed')
}
}
}
And then inside controller or wherever you would need :
public function sendSms($reqid, $recgametype) {
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
}
You can also create custom exception like SMSSendingFailedException and throw it instead of standard \Exception inside send() function.
That will help you to send appropriate response in controller like :
public function sendSms($reqid, $recgametype) {
try{
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
return response()->json('message' => 'SMS sent successfully', 200);
}
catch(SMSSendingFailedException $e){
return response()->json('message' => 'SMS sending failed', 500);
}
}
Then to go one step further, you can use concept of laravel facade if you need it all over the project with a quick class alias.
I wonder how to write proper unit test for my email sending method. It's a problem because inside method I get data from Auth object. Should I send id of user in Request?
public function sendGroupInvite(Request $request){
foreach ($request->get('data') as $item){
$invitations = new \App\Models\Invitations();
$invitations->user_id = Auth::id();
$invitations->name = $item["name"];
$invitations->email = $item["email"];
$invitations->status = 0;
$invitations->token = \UUID::getToken(20);
$invitations->username = Auth::user()->name;
$invitations->save();
$settings = UserSettings::where('user_id', Auth::id())->first();
$email = $item["email"];
$url = 'https://example.com/invite/accept/'.$invitations->token;
$urlreject = 'https://example.com/invite/reject/'.$invitations->token;
$mailproperties = ['token' => $invitations->token,
'name' => $invitations->name,
'url' => $url,
'email' => $email,
'urlreject' => $urlreject,
'userid' => Auth::id(),
'username' => Auth::user()->name,
'user_name' => $settings->name,
'user_lastname' => $settings->lastname,
'user_link' => $settings->user_link,
];
$this->dispatch(new SendMail(new Invitations($mailproperties)));
}
return json_encode(array('msg' => 'ok'));
}
I'm using Auth to get username and user id. When I testing it it's not works, because Auth it's null.
I would go with mocking the queue, something similar to this. Mock Documentation
class MailTester extends TestCase{
/**
* #test
*/
public function test_mail(){
Queue::fake();
// call your api or method
Queue::assertPushed(SendMail, function(SendMail $job) {
return $job->something = $yourProperties;
});
}
You could try "acting as" to deal with the Auth::user().
...
class MyControllerTest extends TestCase{
/**
* #test
*/
public function foo(){
$user = App\Users::find(env('TEST_USER_ID')); //from phpunit.xml
$route = route('foo-route');
$post = ['foo' => 'bar'];
$this->actingAs($user)//a second param is opitonal here for api
->post($route, $post)
->assertStatus(200);
}
}
I am having trouble saving this into database. When I submit my data into database it will only show name_of_bear and all the many relationship stuff(type_of_fish) but not the type_of_bear
Can someone explain to me why it can't work and also maybe give me an example on how it should be done. Thank you
Controller: (this works)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $request->input('name_of_bear')]);
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
But if I were to do this:
Controller : (doesn't work)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name]);
$bear = Bear::create(['bearType' => $bearType]); --> doesn't work if add in this
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
or this:
Controller: (doesn't work)
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name], ['bearType' => $bearType]); --> doesn't work
$bear->fishs()->create(['type_of_fish' => json_encode($fishType)]);
return ('thank you');
}
You can add it like this
$bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);
full code:
public function submit(Request $request)
{
$fishType= $request->input('type_of_fish');
$Name = $request->input('Name');
$bearType = $request->input('bearType');
$bear = Bear::create(['Name' => $Name , 'bearType' => $bearType]);
return ('thank you');
} // removed extra }
For further information you can read documentation
You can just use:
$bear = Bear::create(['Name' => $Name, 'bearType' => $bearType]);
For more info, visit this link.
You can insert data like this:
public function submit(Request $request)
{
$data = array();
$data['type_of_fish']= $request->type_of_fish;
$data['Name'] = $request->Name;
$data['bearType'] = $request->bearType;
$bear = Bear::create($data);
return ('thank you');
}
For more information read Documentation
I would do it like this, assuming that post array keys matches column names.
$bear = Bear::create($request->all()->except(['_token', 'type_of_fish']));