I'm doing an ajax call to controller's method, I made some attempts, but don't know where is the problem.
First try:
public function show(Request $request, $from, $to)
{
//return $request;
$envData = EnviromentalData::whereBetween('data_recorded', array($from, $to))->get();
return TransformService::transform($envData);
}
Output: {"from":["The from field is required."],"to":["The to field is required."]}", responseJSON: Object, status: 422, statusText: "Unprocessable Entity"
And, ofc,those fields 'from' and 'to' have values.
Second try:
public function show(Request $request) {
return $request;
}
Output: undefined
So the question is what is the problem? Also, I added two additional files of routes.php and script.js, I hope it will help.
routes.php
----------
Route::get('dashboard', 'DashboardController#dashboard');
Route::get('dashboard/from/{from}/to/{to}', 'DashboardController#show');
scripts.js
----------
// Ajax call to update the dashboard
function loadChart() {
$.getJSON(window.location.href + '/from/' + fromDate + '/to/' + toDate)
}
You dont have to add Request $request
Try this
routes.php
----------
Route::get('dashboard/from/{from}/to/{to}', 'DashboardController#show');
controller.php
--------------
public function show($from, $to) {
return Response::json($request) ;
}
If you get data from ajax means you have return data as json.
So, I found my problem and it was in two places:
1) return json_encode($request);
2) fixed scripts.js file, added some logic for .done() method and .fail() and all started working!
Related
I'm doing this query in the payment controller and i need to get a post request from the route.
Controller:
class PaymentController extends Controller
{
public function apiPaymentByUserId($date_from, $date_to) {
$payments = DB::table("casefiles, payments")
->select("payments.*")
->where("casefiles.id", "=", 'payments.casefile_id')
->where("casefiles.user_id", "=", Auth::id())
->where("payments.created_at", ">=", $data_from)
->where("payments.updated_at", "<=", $data_to)
->get();
return response()->json([
'success' => true,
'response' => $payments
]);
}
}
Route:
Route::post('/payments/{date_from}/{date_to}', 'Api\PaymentController#apiPaymentByUserId');
How to pass multiple parameters in this post route? Thank you
For post request no need to pass param in url .You will get in request
So route will be
Route::post('/payments', 'Api\PaymentController#apiPaymentByUserId');
and controller method
public function apiPaymentByUserId(Request $request)
{
$date_from = $request->date_from;
$date_to = $request->date_to;
}
If you do not want to change your url, try this in your controller apiPaymentByUserId() method, inject the Request object along with the other path variables like like:
public function apiPaymentByUserId(Illuminate\Http\Request $request, $date_from, $date_to) {
// ... you can access the request body with the methods available in $request object depending on your needs.
}
For POST request no need to pass param in url . Send the Dates as FORM values sent via POST method along with the rest of the FORM values (if any, you're already POSTing in the FORM). You will get all FORM values sent via POST method in Request $request object instance, passed in Controller/Method.
So route will be:
Route::post('/payments', 'Api\PaymentController#apiPaymentByUserId');
and controller method:
public function apiPaymentByUserId(Request $request)
{
$date_from = $request->date_from;
$date_to = $request->date_to;
}
I'm encountering a problem where a redirect from one route to another is calling the targeted controller method twice. This question addresses a similar issue, but the OP passing a 301 status code was deemed to be the issue in the accepted answer, and I'm not specifying any status code. I'm also using the session state for parameters. The relevant code looks something like this:
public function origin(Request $request) {
// Assume I have set variables $user and $cvId
return redirect()
->action('SampleController#confirmUser')
->with([
'cvId' => $cvId,
'userId' => $user->id,
]);
}
public function confirmUser(Request $request) {
$cvId = session()->get('cvId');
$userId = session()->get('userId');
if (is_null($cvId) || is_null($userId)) {
// This is reached on the second time this is called, as
// the session variables aren't set the second time
return redirect('/home');
}
// We only see the view for fractions of a second before we are redirected home
return view('sample.confirmUser', compact('user', 'cvId'));
}
Any ideas what could be causing this? I don't have any next middleware or any of the other possible causes that are suggested in related questions where controllers are executed twice.
Thanks for any help!
Have you tried passing values in parameters? Try the below code.
public function origin(Request $request) {
// Assume I have set variables $user and $cvId
return redirect()->action(
'SampleController#confirmUser', ['cvId' => $cvId, 'userId'=>$user->id]
);
}
public function confirmUser(Request $request) {
$cvId = $request->cvId;
$userId = $request->userId;
if (is_null($cvId) || is_null($userId)) {
// This is reached on the second time this is called, as
// the session variables aren't set the second time
return redirect('/home');
}
// We only see the view for fractions of a second before we are redirected home
return view('sample.confirmUser', compact('user', 'cvId'));
}
I would like to use auth in my login system with two roles:
admin
user.
When I redirect the route to user, it fails.
My Controller:
public function profile($id)
{
$santri = Santri::find($id);
return view('santri.profile', ['santri'=>$santri]);
}
My Route:
Route::group(['middleware' => ['auth', 'checkRole:admin,user']], function () {
Route::get('/santri/{id}/profile', 'SantriController#profile')->name('profiluser');
});
How I check the role:
{
$santri = Santri::all();
if(in_array($request->user()->role,$roles))
{
return $next($request);
}
return redirect()->route('profiluser', $santri);
}
Error:
Missing required parameters for [Route: profiluser] [URI: santri/{id}/profile].
The error message:
Missing required parameters for [Route: profiluser] [URI: santri/{id}/profile].
tells you that you are missing the parameter for this route: profiluser
As you can see here you do not call the route with the correct parameter, you are trying to pass the whole object instead of the id, so instead of this:
return redirect()->route('profiluser', $santri);
Do this:
return redirect()->route('profiluser', $santri->id);
But since you are already passing the whole object you could also do this, lets call it method B.
Here you want to find the model using the passed id:
public function profile($id)
{
$santri = Santri::find($id);
return view('santri.profile', ['santri'=>$santri]);
}
But since you already pass the whole object you could do this:
public function profile(Santri $santri)
{
return view('santri.profile', ['santri' => $santri]);
}
or this, which looks cleaner in my mind:
public function profile(Santri $santri)
{
return view('santri.profile', compact('santri'));
}
You need to pass $santry->id instead of just $santry. Change the line to:
return redirect()->route('profiluser', [$santri->id]);
According to your route:
Route::get('/santri/{id}/profile', 'SantriController#profile')->name('profiluser');
You must pass the user id, like this:
return redirect()->route('profiluser', ['id' => $request->user()->id]);
I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.
Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});
If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});
Everything looks right to me. It's so simple, but I dont know. I've looked everywhere.
Problem: It doesn't redirect. It doesn't give error nothing happens.
But when I enter the browser http://site.dev/fail
it shows "fail" word on screen (so it works).
routes.php:
Route::post('getir' , 'Ahir\Ticket\Controllers\TicketController#postInsert');
Route::get('fail', function() { return 'fail'; });
Route::get('success', function() { return 'success'; });
edit everything
Scenario:
on site.dev/ (homepage) I press submit that form has this.
form action="getir" method="POST" role="form"
so button redirect me to
Route::post('getir' , 'Ahir\Ticket\Controllers\TicketController#postInsert');
so this postInsert is triggered below at controller ticket.
controller ticket:
<?php namespace Ahir\Ticket\Controllers;
use BaseController, Input;
//use Ahir\Ticket\Repositories\TicketInterface;
use Ahir\Ticket\Adapters\AdapterInterface ;
class TicketController extends BaseController {
public function __construct(AdapterInterface $adapter) //TicketInterface $repository
{
//$this->repository = $repository;
$this->adapter = $adapter;
}
public function postInsert()
{
$this->adapter->postInsert();
}
}
then it comes here
codes
public function postInsert()
{
// create the validation rules ------------------------
$rules = array(
'title' => 'required',
'content' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// i added here return vardump('fail'); it displays on screen.
// so i know that program comes here
// but the redirect below neither gives error nor redirect.
//nothing happens here. idk why!
return Redirect::to('fail')->withErrors($validator);
} else {
// validation successful ---------------------------
$this->obj->insert([
'title' => Input::get('title') ,
'content' => Input::get('content')
]);
//here DOESNT work too.
return Redirect::to('success');
}
The problem is that you don't return anything from the calling function.
Your application calls the postInsert() method on your ticket controller. This function calls another function which returns a Redirect.
But you don't pass that returned Redirect back to the application, so the postInsert() function just terminates without any output. The application doesn't know what happens within the postInsert() function, it just waits for something to be returned. And since nothing is returned, the HTTP response is simply empty. In order to pass that Redirect back to the application, you also have to return it from the calling function:
public function postInsert()
{
return $this->adapter->postInsert();
}