Is there a way to pass the information obtained in a Request function to an included page? Consider the following situation - code below works as expected
public function myFunction(Request $request){
$validator = \Validator::make($request::all(), [
'myField' => 'Required',
]);
}
But what I want to do this
public function myFunction(Request $request){
include(app_path() . '/myfunction/validateThis.php')
}
Where the above file named validateThis.php has the validator code inside? Is there a way to get this (Request $request) variable passed through to the include? It returns null right now and I'm not sure if there is a workaround or not
Once the validateThis.php has been included, all you need to do is pass the request object to the function that handles the validation.
Include file that has the validate function
include 'validateThis.php'
call function with the request object passed to it
validate($request)
Create a global variable to save the $request data. Then use global <variable> in your function inside the included file.
Related
I am not getting how to pass data to the controller to update data, below I have given code.
// below is my jquery which I am using to pass form data to the controller.
function editProfile(profileData){
$("#profile_name").val(profileData.name)
$("#profile_id").val(profileData.id);
$("#profile-modal-lg").modal('show');
$("#profile-form").attr('action',"text/edit/"+profileData.id);
}
// below is my route
Route::post('text/edit/{profile}', 'profileController#editProfileData')->name('profile.edit');
// inside controller I am having a function called edit profile
public function editProfileData(Profile $profile,profileRequest $request){
$profile->update($request->all());
return redirect()->back();
}
Is your form method set to 'POST'? If not, try setting the form method attribute to 'POST'. You might also want to add slash at the start of your url to target the absolute url.
$("#profile-form")
.attr('method', 'POST')
.attr('action', `/text/edit/${profileData.id}`);
In order to consolidate some bulky code in a controller I have been able to do this inside function
public function myCustomFunction(Request $request){
include(app_path() . '/myFunctions/myCustomFunction1.php');
}
It does successfully work but by doing the include, I noticed it doesnt carry the namespace and/or other variables set in the controller.
If its just a simple model it needs I was able to add
Use \App\myModel;
to the top of the controller and it runs the code just fine as if its part of the controller.
What I am having issue with is when I want to run validation. I cant figure out what to "use" to work on the included page.
If I run my logic in the controller without doing include it works, but if put inside the include it does not, and I get NO errors either.
I tried this inside the include page to activate the validation from within
the include file
namespace App\Http\Controllers;
use Validator;
use Request;
which mimics the original controller, but still does not work. Is what I'm trying to do possible but I'm doing something wrong? Or am I doing something that will never work? If all else fails I can keep the code within the actual controller to make it work, but I'm trying to accomplish some sort of clarity on complex controllers. Such as...
public function myCustomFunction(Request $request){
if(request('value1')=='1'){
include(app_path() . '/myFunctions/myCustomFunction1.php');
}else{
include(app_path() . '/myFunctions/myCustomFunction2.php');
}
}
This structure is already working on anything that doesn't need validation so I'm hoping there is a simple way to hook the include page into the same set of validation tools the original controller has access to.
In the controller, so include the files incorrectly. It's best for you to create a Helpers folder in the app folder, in it create classes with your functions.
namespace App\Helpers;
class HelpersOne {
public function myFunctionOne(){.../*youre code*/}
public function myFunctionTwo(){.../*youre code*/}
}
And already in your controller you can call these classes.
use App\Helpers\HelpersOne;
...
public function myCustomFunction(Request $request){
if(request('value1')=='1'){
$myFunction = new HelpersOne();
$myFunction->myFunctionOne();
}else{
$myFunction = new HelpersTwo();
$myFunction->myFunctionTwo();
}
}
In Laravel, I have an Eloquent Model Person and a function getSomestringFromPerson() which is operating on the Model Person and returning a string. Now I have an AJAX request whose response is a collection of Persons. Until here I know what to do.
Now, in the JavaScript I would like do display the result of getSomestringFromPerson() for each Person in the response.
Is that possible? If yes, how? Or do I have to run the function in the Controller and include the result in the AJAX response? (That looks a bit cumbersome to me...)
In the controller that handles the AJAX request, I assume it gets a collection of People like something like this (at a bare minimum):
public function handleAjax(Request $request){
$people = People::get();
return response()->json(["people" => $people], 200);
}
And then in your JS a function for handling the response:
$.get(URL, function(data){
console.log(data); // Collection (js object) of `People` models.
});
In your handleAjax function, you would loop over each of your People and assign a property to hold the value of $person->getSomestringFromPerson():
foreach($people AS $person){
$person->someString = $person->getSomestringFromPerson();
}
Then, in your Javascript code, you would be able to access it like so:
for(var person in data.people){
console.log(data.people[person].someString); // Should return the expected value of `$person->getSomestringFromPerson();` as defined in your function.
}
From there, you should be able to do whatever else it is you'd need to do with your data.people object.
I am trying to call a method inside a controller in MVC from a javascript action. The javascript action is supposed to invoke this method inside the controller and send some parameters to it.
My Javascript code looks like this:
location.href = '#Url.Content("~/Areas/MyArea/MyMethod/"+Model.MyId)';
My Method is defined as follows:
[HttpGet]
public ActionResult MyMethod(int? MyId)
{
doSomething(MyId);
return View("MyView");
}
However, when i debug the application, when the method is called the MyId parameter is passed as null and not as the current value of the MyId parameter in my model. What can I do to correctly send or retrieve this value? Thanks!
In your route definition I suppose that the parameter is called {id} and not {MyId}:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyArea_default",
"MyArea/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
So try to be more consistent and adapt your controller action parameter name accordingly:
[HttpGet]
public ActionResult MyMethod(int? id)
{
doSomething(id);
return View("MyView");
}
Also you probably wanna use url helpers instead of hardcoding some url patterns in your javascript code:
window.location.href = '#Url.Action("MyMethod", "SomeControllerName", new { area = "MyArea", id = Model.MyId })';
The Url.Content helper is used to reference static resources in your site such as javascript, css and image files. For controller actions it's much better to use the Url.Action helper method.
I'm trying to get JSON-data into a jQuery variable using ASP.NET (not MVC):
$(document).ready(function () {
$('#calendar').fullCalendar({
events: GetEvents(start, end) //This line is invalid
}
}
In MVC, it could just be events: "/Calendar/GetEvents/", which would call the CalendarController's GetEvents()-method.
But since I'm not using MVC I started following this guide to try calling server-side methods from the client.
In the second step it tells me that I have to create a static method in order to do this:
[System.Web.Services.WebMethod]
public static string Message()
{
return "Hello from the server-side World!";
}
But I need to be able to access non-static variables like Session[] inside the method, so I can't really see how this approach would work.
Is there a better approach to getting JSON-data extracted from an aspx.cs-method that doesn't involve making direct server-side calls? Or is there a way for me to use the Session that I'm not aware of?
Instead of calling Session directly use HttpContext.Current.Session, or make it a static property in your page:
private static HttpSessionState MySession
{
get
{
return HttpContext.Current.Session;
}
set
{
return HttpContext.Current.Session = value;
}
}