How do I properly call a Laravel Route or Controller in my Ajax?
An error appears and says:
Route [product/create] not defined. (View:
C:\xampp\htdocs\laravel\resources\views\jsBlade\logoInput.blade.php)
(View:
C:\xampp\htdocs\laravel\resources\views\jsBlade\logoInput.blade.php)
My Routes look like this:
# Middleware group if user is successfully logged in
Route::group(['middleware' => 'auth'], function ()
{
Route::get('/home', ['as' => 'home', 'uses' => 'PageController#showHome']);
# Product group
Route::group(['prefix' => 'product'], function ()
{
Route::get('/', ['as' => 'indexProduct', 'uses' => 'ProductController#indexProduct']);
Route::get('new', ['as' => 'newProduct', 'uses' => 'ProductController#newProduct']);
Route::get('show/{productID}', ['as' => 'showProduct', 'uses' => 'ProductController#showProduct']);
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
Route::post('create', ['as' => 'createProduct', 'uses' => 'ProductController#createProduct']);
Route::post('update', ['as' => 'updateProduct', 'uses' => 'ProductController#updateProduct']);
Route::delete('destroy', ['as' => 'destroyProduct', 'uses' => 'ProductController#destroyProduct']);
});
});
My Ajax:
$("#input-logo").fileinput({
uploadUrl: '{{route("product/create")}}',
type: 'POST',
allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
allowedFileTypes: ['image'],
headers: {
'X-CSRF-Token': $('#_token').val(),
}
}).on('filepreupload', function() {
$('#kv-success-box').html('');
}).on('fileuploaded', function(event, data) {
$('#kv-success-box').append(data.response.link);
$('#kv-success-modal').modal('show');
});
</script>
Controller
<?php
namespace App\Http\Controllers;
use Input;
use App\Product;
use App\Companies;
use App\Http\Controllers\Controller;
class ProductController extends Controller
{
public function createProduct()
{
$data = Input::all();
$product = new Product;
$product->fill($data);
if($product->save())
{
return redirect()->route('root')->with('message','Success');;
}
}
}
Firefox gives this error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data.
Change this part
uploadUrl: '{{route("product/create")}}',
to this
uploadUrl: '{{url("product/create")}}',
and add a csrf token to your header in ajax
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
Just Ajax to the URL of the route like this:
This is my route:
Route::post('users/send-file-temp',['uses'=>'UsersController#postSendFileTemp']);
and here is my ajax call:
$.ajax({
url: '/users/send-file-temp',
});
Ajax will send the request to /users/send-file-temp and Laravel will recognize the route and direct it to the corresponding controller.
Take not of your ajax method type and your Route method type
Example below
My Ajax code
$('#sendMsg').click(function(e){
e.preventDefault();
$.ajax({
url: '{{url("R_E/users/sendMSG")}}',
data: $("#form-signin").serialize(),
type: "POST",
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function(data){
alert("okay");
},
error: function(){
alert("failure From php side!!! ");
}
});
});
My route Code
Route::post('/users/sendMSG', 'RE\MainController#sendMSG');
instead of {{route("product/create")}} ,
following one worked for me in Laravel 8 :
!{route("product/create")}!
Related
I have this route defined
Route::get('test/something/{id?}', 'MyController#mymethod')->name('test.something');
So if go to domain_1.com/test/something/123 I get some page with data.
Now, I want to to show the exact same thing if the site if accessed form another domain with subdomain. I've defined this:
Route::group(['domain' => 'subdomain.domain_2.com'], function() {
Route::get('/', 'MyController#mymethod', ['id' => 123]);
});
but I got to subdomain.domain_2.com, I get Too few arguments error. How can I pass the id parameter to the method in the route?
You could use redirect like:
Route::get('test/something/{id?}', 'MyController#mymethod')->name('test.something');
Route::group(['domain' => 'subdomain.domain_2.com'], function() {
Route::get('/', function(){
return redirect('/test/something/123');
});
});
If you don't want to use redirect, you could check the current url from the method in the controller like:
public function mymethod($id=null){
$currentUrl = request()->url();
if (strpos($currentUrl, 'subdomain') !== false) {
$id = 123;
}
// your function
}
I've found this piece of code that gets the job done, but I'm not sure is the correct way to achieve what I want
Route::group(['domain' => 'subdomain.domain_2.com'], function()
{
Route::get('/', [ 'as' => 'some_alias', function()
{
return app()->make(App\Http\Controllers\MyController::class)->callAction('mymethod', $parameters = [ 'id' => 123 ]);
}]);
});
I know this is a basic laravel question but don't know how do it. How can I add one route to 2 different middleware (auth) without having to duplicate it?
// =admin
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});
// =cashier
Route::group(['middleware' => ['auth', 'role:cashier']], function() {
Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController#showCashierProfile')->name('dashboard.cashier.profile');
Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});
I have this route and I don't want to repeat calling this per auth middleware: Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
You can't have two routes with the same url.
Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
This route is inside both groups and since the url they will produce will be the same, only the second will remain.
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
//Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
// this route will be ignored because the other one has the same url
});
Route::group(['middleware' => ['auth', 'role:cashier']], function() {
Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController#showCashierProfile')->name('dashboard.cashier.profile');
Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});
If you want Laravel to handle these two routes differently, you have to add a prefix:
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => ['auth']], function() {
Route::get('/dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
//Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
// this route will be ignored because the other one has the same url
});
Route::group(['prefix' => 'cashier', 'as' => 'cashier.', 'middleware' => ['auth', 'role:cashier']], function() {
Route::get('/dashboard/cashier/profile', 'App\Http\Controllers\DashboardController#showCashierProfile')->name('dashboard.cashier.profile');
Route::get('make-a-sale', [PurchasesController::class, 'index'])->name('make-a-sale.index');
});
This way, when the url will be prefixed with admin, the first route will be called (without the role:cashier middleware).
Notice that I added a route name prefix ('as' => 'admin.' / 'as' => 'cashier.') so you can call each one by name, using:
route('admin.make-a-sale.index'); // admin/make-a-sale
//or
route('cashier.make-a-sale.index'); // cashier/make-a-sale
Just to add, if someone wants to fix the Laravel blade error below whenever you clear your browser cache and was automatically logout:
*Attempt to read property "name" ...*
You need to add all your routes inside the:
Route::group(['middleware' => ['auth']], function () {
// routes here
});
This will redirect you to login once that happens.
I have this group in my route:
}
Route::group(['prefix' => 'v1/en'], function() {}
is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:
Route::group(['prefix' => 'v1/{lang}'], function() {}
Yes you can, $lang will be available if you define your route group like this:
Route::group(['prefix' => 'v1/{lang}'], function() {
// ...
});
or with new syntax:
Route::prefix('v1/{lang}')->group(function() {
// ...
});
You can access it anywhere with:
request()->route()->parameter('lang');
You might want to checkout packages like this: Localization for Laravel
They basically do the same, and have nice middleware implementations to set locales etc.
How about to generate dynamically another route group with prefix $lang inside of group with v1 prefix?
$langs = ['en', 'de', 'it'];
Route::group(['prefix' => 'v1'], function() use ($langs) {
foreach($langs AS $lang) :
Route::group(['prefix' => $lang], function() {
Route::get('something', 'SomethingController#list');
});
endforeach;
});
or same logic (taken from here):
Route::group(['prefix' => 'v1'], function() use ($langs) {
Route::group(['prefix' => '{lang}'], function() {
Route::get('something', 'SomethingController#list');
});
});
Hi I was wondering why my Laravel 5 Ajax request doesnt work
<input type="hidden" class="_token" value="{{Session::token()}}" name="_token">
$.ajax({
url: "{{ route('groups.store') }}",
method: 'post',
data: {
name: 'name',
_token: $("input[name=_token]").val()
},
success: function(response) {
if (response.success == true) {
// remove error message
alert('success');
}
},
error: function(xhr) {
alert('error');
}
});
on the Route File I put:
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
and on my controller I put:
public function store(Request $request)
{
return response()->json(['success' => true]);
}
then I keep getting error 404 while I simply wants to display the json result from my controller much help appreciated thx
btw heres the full routes.php
<?php
carbon()->setLocale('id');
Route::get('/', function () {
return view('welcome');
});
Route::post('search/SearchController','SearchController#postMapSearchResult');
Route::get('/getRequest', function(){
if(Request::ajax()){
return 'getRequest has loaded';
}
});
Route::group(['middleware' => ['web']], function () {
// Backend Area
Route::controller('login','Backend\LoginController');
Route::get('admin-cp' , function(){
return redirect('login');
});
if(request()->segment(1) == webarq()->backendUrl)
{
include __DIR__.'/backendRoutes.php';
}
//
// Frontend Area
Route::get('account/confirmation/{token}', 'Auth\AuthController#activateUser')->name('user.activate');
Route::controller('faq','FaqController');
Route::controller('blog','BlogController');
Route::controller('social','SocialController');
Route::controller('account','AccountController');
Route::controller('iklan','IklanController');
Route::controller('search','SearchController');
Route::controller('/','HomeController');
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
});
Put the route outside of middleware group
Below is a code which work perfect for me.
var count = 100;
$('#ID').on("click", ".CLASS",function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'URL',
type: 'POST',
data: {_token: CSRF_TOKEN,id:count},
dataType: 'html',
success: function (data) {
alert('success');
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
I've two route controllers within a route group:
Route::group(array('before' => 'auth'), function()
{
Route::controller('dashboard/', 'DashboardController');
Route::controller('dashboard/profile', 'DashboardProfileController');
});
That works until I add prefix key to the array:
Route::group(array('prefix' => 'dashboard', 'before' => 'auth'), function()
{
Route::controller('/', 'DashboardController');
Route::controller('/profile', 'DashboardProfileController');
});
It's weird as the first route controller works since I can access localhost/dashboard but the second fails on localhost/dashboard/profile and or localhost/dashboard/profile/edit
What's wrong here?!
It seems both of them route to one location, therefore the longest one should go first because it is interpreted as argument.
Route::group(array('prefix' => 'dashboard', 'before' => 'auth'), function()
{
Route::controller('/profile', 'DashboardProfileController');
Route::controller('/', 'DashboardController');
});