How to construct a route model binding url with axios? - laravel

I want to write a vue Axios URL with slug and id, but I can't.
Please help me.
axios.get('http://localhost/BUproject/postsByUser/' + slug / +id)
.then(response => {
this.postsByUser = response.data;
Vue.filter('myOwnTime', function (value) {
return moment(value).fromNow();
});
});

It looks like from your code the placement of the quotes and + is not quite adding up properly.
You can do good old fashioned string concatenation:
'http://localhost/BUproject/postsByUser/' + slug + '/' +id'
Or if using ES6, you can do
`http://localhost/BUproject/postsByUser/${slug}/${id}`
Also if the call will always be to the same server as you are working in, you can ditch the http://localhost part to make it relative to the root.
`/BUproject/postsByUser/${slug}/${id}`
All you ever wanted to know about String in javascript

Related

How to setup url in JavaScript to pass multiple parameter to controller in Laravel without using request

I setup the url by JavaScript to call a function in controller with only one parameter($RoleID) like this
$(document).on('change','#role',function(){
$RoleID = $(this).val();
let $url = '{{route("Admin.role.permission.LoadMember",':id')}}'
$url = $url.replace(':id', $RoleID);
$.ajax({
url:$url,
success:function(data)
{
$('#member').append(data);
}// end fucntion success
});
});
It works ok, Now I would like to do the same with more than one parameter without using Request
I tried like this
document.getElementById('function').addEventListener('change', function(e) {
if (e.target.name==='function') {
$FncID = e.target.value;
let $url = '{{route("Admin.role.permission.LoadActionsInRolePermissions",'[$ModuleID,$RolID,$FncID]')}}';
$.ajax({
url:$url,
success:function(data)
{
$('tbody').html(data);
//$('#member').append(data);
}// end fucntion success
});
}
})
But unfortunately, It is not work. Pls help me.
Thank in advance
You haven't shown us how you defined the route, nor what laravel version you're using, but I highly suggest taking a read on the docs on how route parameters work.
As example, say this is your LoadMember route:
Route::get('permission/load-member/{id}', [PermissionController::class, 'loadMember'])->name('Admin.role.permission.LoadMember')
Then, as follows:
{{route("Admin.role.permission.LoadMember",['id' => ':id'])}}.
By passing an associative array with key => value assignment, Laravel knows where to place the given values in the url.
For a multi-parameter route, it works exactly the same:
Route::get('permission/load-actions-in-role-permissions/{moduleId}/{rolId}/{fncId}', [PermissionController::class, 'loadActionsInRolePermissions']) ->name('Admin.role.permission.LoadActionsInRolePermissions')
{{route("Admin.role.permission.LoadActionsInRolePermissions",'['moduleId' => $ModuleID, 'rolId' => $RolID, 'fncId' => $FncID]')}}
Also, may I suggest using camelCase for variable names, and kebab-case or snake_case for route naming? It highly improves readability and future developers who might work on your project will have a better guess at how your route structure works.

axios get passing parameter to laravel route

I am trying to pass an id through axios.get in vue.js to laravel route.
my axios code plus parameter are as following,
axios.get('http://localhost/laravel_back/public/api/bpaper',{
params: {
id:12
}
and my laravel route is as follows,
Route::get('bpaper/{id}', function($id)
{
return 'Paper '.$id;
});
when executing this code i get a 404 error on my browser console. and the request url is,
Request URL:http://localhost/laravel_back/public/api/bpaper?id=12
I have already given the access-control allow methods to allow communication through axios. And the code runs when not providing a parameter. any one know a fix.
Considerind server-side is Route::get('bpaper/{id}', function($id) { ..., the id is part of the path, not a parameter. Add it to the URL. Do:
var myId = 12;
axios.get('http://localhost/laravel_back/public/api/bpaper/' + myId)
Added it to a myId variable for clarity, you don't have to do it. Using:
axios.get('http://localhost/laravel_back/public/api/bpaper/12')
would work just as well.
Also, if you have access to newer versions of JavaScript, you can profit from template strings:
var myId = 12;
axios.get(`http://localhost/laravel_back/public/api/bpaper/${myId}`)

How to use the web api url across the mvc application

here is my piece of sample code
function AuthenticateLogin() {
$.getJSON('http://localhost:52293/api/APILogin/', function (data) {
if (data != null) {
}
}
);
}
The hosting url is below, which will be used across the mvc application, might be the controller/action will be varied across the application.
http://localhost:52293
for example, here i have hard coded the above url in all places, If I'm moving the application to other machine,then it is not good to change the url again in each and every places. so, is there any way to handle this ?
Give your API action a static name:
[RoutePrefix("api/APILogin")]
public class APILoginApiController {
[Route("", Name = "Login")]
public ActionResult Login(string userName) {
// ...
}
}
Then in your Razor JavaScript, you can utilize the UrlHelper by calling Url.HttpRouteUrl to dynamically build your URL for you.
$.getJSON('#Url.HttpRouteUrl("Login", new {})', function (data) {
// ...
});
The advantage of this approach is that if you change anything about how the route is formulated, it's in the [Route] attribute on the action. Matching the name like that will use the routing engine to always create the correct path. Otherwise, you're still stuck with (partial) hard-coded paths throughout your JavaScript.
If your route requires any variables, then that is provided within the empty anonymous object as the second parameter for HttpRouteUrl().
You should not hardcode the full absolute url like that. You may consider using the relative url. To generate relative url, you may consider using the Url helper methods
If your code is inside an external js file, you should consider using the helper method to generate the relative url in your razor view(s) and store it in a js variable which you can use in your external js files.
In your razor view
<script>
var myApp = myApp || {};
myApp.siteBaseUrl = "#Url.Content("~")"; // Get the app root
</script>
Now in your external js files
$.getJSON(myApp.siteBaseUrl+'api/APILogin/', function (data) {
// do something
});
You can also use Url.RouteUrl helper method to generate the urls to the api endpoints. For example
var myApp = myApp || {};
myApp.productsApiUrl = "#Url.RouteUrl("DefaultApi",
new { httproute = true, controller = "Products"})";
Now somewhere else in the js codde, you can use it like
$.getJSON(myApp.productsApiUrl , function (data) {
// do something with products data
});
This approach allows you to pass route values when you make the call and the helper method will build the url for you (based on the route definition)
myApp.productsDetailsUrl = "#Url.RouteUrl("DefaultApi",
new { httproute = true, controller = "Products", id= 210 })";

AJAX request becomes invalid due to prepending of URL before sent to server

I have a problem with my ajax requests to an api controller in ASP.NET MVC 5.
My scenario is like this:
I have an api controller like this:
[RoutePrefix("api/organizations/{orgId:int}/students")]
class StudentController{
[Route("subjects")]
[HttpGet]
public HttpResponseMessage GetSubjects(int orgId)
{
}
}
And in my .js file I have a code for calling that request with the specified url like this:
var baseURL = "api/organizations/" + $("#orgId").val() + "/students";
$.get(baseURL + "/subjects").done(function (subjects) {
$.each(subjects, function (index, val) {
var vm = new SubjectVM();
vm.Id(val.Id);
vm.Name(val.Name);
self.Subjects.push(vm);
});
});
But the problem is it will not go into that controller method because its url looks like this http://localhost:10927/students/api/organizations/15/students/subjects
What it should be is like this http://localhost:10927/api/organizations/15/students/subjects so that it will go in.
What I'm confused of was when I'm in the student main page with url like this http://localhost:10927, all is well. The url it produced is correct. But when I'm on the http://localhost:10927/student/create page it will produced the said url.
Does anyone here have an idea of what was happening? Hopefully you can help me here.
Thank you.
Change your baseURL variable to start with a forward slash: /
Doing this forces the URL to be built from the root of the host, rather than the current directory.

Laravel passing all routes for a particular domain to a controller

Working on a Laravel 4.2 project. What I am trying to accomplish is pass every URI pattern to a controller that I can then go to the database and see if I need to redirect this URL (I know I can do this simple in PHP and do not need to go through Laravel, but just trying to use this as a learning experience.)
So what I have at the moment is this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('?', 'RedirectController#index');
});
I am routing any subdomain which I deem as a "redirect subdomain" ... The ? is where I am having the problem. From what I have read you should be able to use "*" for anything but that does not seem to be working. Anyone have a clue how to pass any URL to a controller?
And on top of that I would ideally like to pass the FULL URL so i can easily just check the DB and redirect so:
$url = URL::full();
Try this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('{path}', 'RedirectController#index')
->where('path', '.*');
});
And your controller will reseive the path as first argument
public function index($path){
// ...
}
In case you're wondering, the where is needed because without it {path} will only match the path until the first /. This way all characters, even /, are allowed as route parameter

Resources