i have a question about ajax requests. is there a solution to define a rout just for ajax requests before controller??
i always use a Condition like this in the related method:
public function ajaxRequest(Request $request)
{
if ($request->ajax())
{
...
}
}
thanks for your help
A route cannot be defined only for ajax requests without some type of key.
But ajax requests can be defined before controller without a controller at routes/web.php
Route::get('/crud', function(){
//get
return \App\Models\Products::all();
});
Route::post('/crud', function(){
//set
return \App\Models\Products::update([
'product_name' => (new \Illuminate\Http\Request)['name_product']
]);
});
...
Related
OrderController.php
if (request('payment_method') == 'online') {
return redirect(route('payments.pay', $order->id));
}
web.php
Route::POST('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');
PublicSslCommerzPaymentController.php
session_start();
class PublicSslCommerzPaymentController extends Controller
{
public function index(Request $request, $ordId)
{
//code...
}
}
Here in index function I need the order id from `OrderController.
But the Error I am getting
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
if you want to redirect to named route you can use this:
return redirect()->route('payments.pay', ['orderId' => $order->id]);
if you want generate redirect to controller action you can try this:
return redirect()->action(
'PublicSslCommerzPaymentController#index', ['ordId' => $order->id]]
);
Just change in your web.php from POST method to GET method
Something like this
Route::GET('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');
I'm trying to redirect a route from a controller function after a form submit process in Laravel 5.4 as it is said in link below
https://laravel.com/docs/5.4/redirects#redirecting-named-routes
Route;
Route::group(['middleware' => ['api'], 'prefix' => 'api'], function () {
Route::post('doSomething', 'Page#doSomething');
});
Route::post('/profile', function () {
//..
});
Controller;
public function doSomething(Request $request){
return redirect()->route('profile', ['id'=>1]);
}
When I try to redirect I get this error.
InvalidArgumentException in UrlGenerator.php line 304: Route [profile]
not defined.
I have searched several times about redirection but I got similar results.
Any suggestions ? Thank you.
route() works with named routes, so name your route
Route::post('/profile', function () {
//..
})->name('profile');
I am using Laravel and vue-resource,in this demo below:
{
var formData = new FormData();
formData.append('foo', 'bar');
formData.append('pic', fileInput, 'mypic.jpg');
this.$http.patch('/someUrl/'+itemId, formData,{
before(request) {
if (this.previousRequest) {
this.previousRequest.abort();
}
this.previousRequest = request;
}
}).then((response) => {
this.items[index].price = response.data.price;
}, (response) => {
//console.log(response.data);
window.location.href = "../../login";
});
}
controller:
class CartController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function update(Request $request, $id)
{
$goods = Goods::findOrFail($id);
$goods->amount = $request->get('amount');
$goods->save();
$price = Price::findOrFail($id);
return $price;
}
}
Ajax request access update method of CartController,
If login,ajax request is successful,it can work.
I want to let it jump to login page if login status is expired,
and I test it,the error in debugging tools is like this:
But the page doesn't jump.
How to let it jump?
You can add your web routes under the auth middleware:
Route::group(['middleware' => 'auth'], function(){
Route::get('/', 'HomeController#index')->name('home');
// Add all your non-api routes.
});
This will not resolve the redirection after the callback, but will prevent you to access to the page where the request is fired if you are not logged in, supposing that your form is in the same application that your API.
The error you are getting is because of CSRF Token.
In your head section add this
<meta id="csrf-token" name="csrf-token" content="{{ csrf_token() }}"/>
And in the Vue app file add this
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#csrf-token').getAttribute('content');
Regarding the redirection kindly share a bit more information as to the response from the server if the user is not authorised.
Add your route url to VerifyCsrfToken.php file. So it will avoid token verification.
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
//url go here
];
}
Following is my routes where I am calling my Controller directly in route.
How can I pass Request $request to my getBlog Function.. Or is there any way to directly get $request object in my getblog function of controller ???
$artObj = App::make('App\Http\Controllers\Front\ArticleController');
return $artObj->getBlog($id);
Code in Routes:
Route::get('/{slug}', function($slug) {
// Get Id and Type depending on url
$resultarray = App\Model\UrlAlias::getTypefromUrl($slug);
if(!empty($resultarray)) {
if($resultarray[0]['type'] == 'article') {
$id = $resultarray[0]['ref_id'] ;
$artObj = App::make('App\Http\Controllers\Front\ArticleController');
return $artObj->getBlog($id);
} else {
return Response::view("errors.404", $msg, 400);
}
} else {
return Response::view("errors.404", array(), 400);
}
});
You can do in the head of the routes.php file:
use Illuminate\Http\Request;
And then in the beginning of your route:
Route::get('/{slug}', function($slug, Request $request) {
And the $request will be available to you. But that is extremely bad practice. What you should do - is move the whole logic into the controller like that:
Route::group(['namespace' => 'Front'], function(){
Route::get('/{slug}', 'ArticleController#methodName');
});
and then you can use the Request class in your controller class and the controller method:
<?php
namespace App\Http\Controllers\Front
use Illuminate\Http\Request;
class ArticleController
{ ...
public function methodName(Request $request){
...function implementation...
}
...
}
The Request is a global variable, you can access it anywhere with either php code or even some helper Laravel functions.
Just use request() and it's the same as passing the request as an object inside a variable through a function. (It's equivalent to the Request $request variable received).
It improved readability also. Just remember you can't change request objects directly, you'd better use request()->merge(['key' => 'newValue']);
In laravel 5, we can now use the Request classes for input validation like so :
public function store(StoreItemRequest $request)
{
$item = Item::create($request->all());
return 'success';
}
When the validation fails, I can get the errors thanks to the response function in the Request class :
public function response(array $errors) {
return response()->json(['errors' => $errors]);
}
But what if the validation succeeds? Is there a function that would get automatically triggered like so :
public function ????(){
if($request->ajax())
return response()->json(['success' => true]);
}
Note: it is required that the content of the function store does NOT get executed if the request is ajax (just as it would not get executed if the validation fails).
Yeah, I found validate method in ValidateWhenResolvedTrait which you could override in your form request class;
public function validate(){
$instance = $this->getValidatorInstance();
if($this->passesAuthorization()){
$this->failedAuthorization();
}elseif(!$instance->passes()){
$this->failedValidation($instance);
}elseif( $instance->passes()){
if($this->ajax())
throw new HttpResponseException(response()->json(['success' => true]));
}
}
Currently there is no such method. You can do this in your request with some "hacks" (like override validate method) but I do not recommend it.
Idea of Request was to move validation/authorization out of controller. If you move successful response to Request than we have the same situation as before (well, name changed).
I would suggest to let controller handle ajax too:
public function store(StoreItemRequest $request)
{
$item = Item::create($request->all());
if($request->ajax())
return response()->json(['success' => true]);
return 'success';
}
Is there a reason why you are trying to achieve this in a request?