Laravel: href with route in jQuery - php

I'm trying to create href with route laravel. This route contains a parameter, but it always returns Error 404. I don´t know what I´m doing wrong.
I know that my question is very easy, I´m searching in Google for this, but I think that I'm doing well on my route.
My route:
/** SHOW EVENT INFO */
Route::get('event/{url}', 'Web\EventController#showEvent');
My href in file.js:
<a target="_blank" id="button-event-read" href="'+config.url.base_url+'event/'+eventUrl+'" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>
If I click in href, it goes to the correct route but ends up showing Error 404.
My controller:
public function showEvent($url){
echo "here";
}

you can use route name
add a name to your route:
/** SHOW EVENT INFO */
Route::get('event/{url}', 'Web\EventController#showEvent')->name('MyRouteName');
and use the route name in href:
<a target="_blank" id="button-event-read" href="{{route('MyRouteName', 'MyParameter')}}" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>

Get Host url in variable
var url = window.location.protocol + "//" + window.location.host;
and then use it in href like this.
<a target="_blank" id="button-event-read" href="'+url+'/event/'+eventUrl+'" class="btn color2-bg float-btn">Leer más.<i class="fal fa-angle-right"></i></a>

Related

Not found page when clicked detail to get data based on id

I have been fixing this trivial problem a few days, but it didn't solve either.
When I click the detail button on the table, it will display a 404 or not found message.
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik');
}
Route
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail']);
Blade
<a class="btn btn-success btn-sm" href="{{ url('admin/lirik-lagu/detail', $data->id) }}">Detail</a>
I will try to fix what i think it's wrong in your code.
First you should give the $data to your blade file
Controller method
public function detail($id)
{
$data = DB::table('lirik_lagu')->where('id', $id)->first();
return view ('admin.detail-lirik',['data'=>$data]);
}
Second, your should omit the $ in your Route id parameters
Route
Route::get('lirik-lagu/detail/{id}', [LirikLaguController::class, 'detail']);
Third, when you generate the url url(...) it seems to have an admin prefix but not your route declaration.
Blade
<a class="btn btn-success btn-sm" href="{{ url('lirik-lagu/detail', $data->id) }}">Detail</a>
You are not passing the variable to the view. This is how you do it:
return view('admin.detail-lirik', $data);
If you need to pass multiple variables you can pass an array in the second paramter like this:
return view('admin.detail-lirik, ["varname" => $var]);
I see several problems here, so I'm going to point them out. First one, you never returned the data to your view:
return view ('admin.detail-lirik', $data);
The other is the URL in your blade file. You called admin/lirik-lagu/detail but you defined route without admin in your web.php file. You can remove the admin from your url, or create a name for your route and call it that way:
Route::get('lirik-lagu/detail/{$id}', [LirikLaguController::class, 'detail'])->name('lirik-langu');
And then use it like this
<a class="btn btn-success btn-sm" href="{{ route('lirik-langu', $data->id) }}">Detail</a>

Can't navigate the page in laravel project

I have created addnewemployee.blade.php in the views folder. In routes, I have mentioned
Route::get('/addnewemployee', function() {
return view('addnewemployee');
});
As well as I have given the path in my enter code herehome page like
<a class="btn cus-button" href="{{url('/addnewemployee')}}"> Add New </a>
Once I click the add new button, 'addnewemployee' is added with my URL but it shows 404 not found.
Can anyone please help me?
The addnewemployee.blade.php should be in hte resources/views/addnewemployee.blade.php in order for it to work.
Try the named route:
Route::get('/addnewemployee', function() {
return view('addnewemployee');
})->name('addnewemployee');
<a class="btn cus-button" href="{{ route('addnewemployee') }}"> Add New </a>

Why is blade directives used in Roles and permission? Explain me the example below here

I'm given with a task of adding new features in a built-in application and I end up with a piece of code. I have no idea how its working.
On AppServiceProvider.php
Blade::directive('hasRole', function ($expression) {
$exp=explode(",",$expression);
return "<?php if(Auth::user()->hasPermission($exp[0],$exp[1])): ?>";
});
On blades:
#hasRole('travel_calendar','view')
<button class="btn btn-space btn-default btn-big tactive" id="travel_menu_cal" ><i class="icon mdi mdi-calendar"></i> Calendar</button>
#endHasRole
What does the view does in this code too.
Someone place explain me the code.
From top to bottom with inline comments:
// Declare a custom function with name 'hasRole' that can be used in Blade files
Blade::directive('hasRole', function ($expression) {
// If there are comma's in the expression, split those and dump the resulting strings in an array
$exp=explode(",",$expression);
// Return some php code that evaluates to pseudocode:
// if user has permission to expression
return "<?php if(Auth::user()->hasPermission($exp[0],$exp[1])): ?>";
});
// Use defined function, expression exists of two string: travel_calendar and view
#hasRole('travel_calendar','view')
<button class="btn btn-space btn-default btn-big tactive" id="travel_menu_cal" ><i class="icon mdi mdi-calendar"></i> Calendar</button>
#endHasRole
The whole thing basically evaluates to this:
If user has permission to view travel_calendar
Then show button

How to populate view with database information after AJAX request

Hi there once again SO community. I've been developing a site and so far it's going pretty well. But today after a long day searching for a solution I can't understand nor find what the right path is...
I want to click on a button and a profile page where you can edit the fields appear. I can redirect to the page I want but I don't know how to send the user data so I can populate the fields.
Here is my button code on my view
<button class="btn btn-xs btn-warning dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="false" style="border-color: black" id="dados_{{ $user->username }}"> Alterar Dados Pessoais
<i class="glyphicon glyphicon-cog"></i>
</button>
Here is the button AJAX request handler
if((this.id).indexOf("dados") != -1){
var content = this.id.replace("dados_", "");
$.get('callPermissions', {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
And here is my callPermission Controller
public function callPermissions(Request $request)
{
if($request->ajax()){
$usernames = Input::get('usernameSend');
if(isset($usernames)){
$user = User::Where('username', '=', $usernames)->first();
$returnHTML = view('userOptions.settings')->render();
return view('userOptions.settings');
}else{
Log::warning("Username não existe na base de dados.");
}
}
}
and here my Settings Controller
public function settings(Request $request)
{
return view('userOptions.settings');
}
And here is the route
Route::get('/callPermissions', 'SidebarController#callPermissions');
I know the controller is wrong and from what I've read I should verify if the AJAX is successful and if it is handle i on the AJAX request. But from what I've understand I'm not using the Controller at all (even though it goes there). How should I send the user information (in this case the username, then I can get everything from the database) and then send it to the view? I've been searching and trying out stuff that doesn't work...since the return view("your_view") on the Controller doesn't work.
Sorry if I've been confusing and if you need additional information feel free to ask!
Thanks for your help!!
Edit: If I return this on the controller
return view('userOptions.settings', compact('user'));
and do a replace with the Ajax request as show above and add this to the settings view
<p> {{ $user->name }} </p>
I get the following error Undefined variable: user (View: C:\wamp64\www\siteXL\ideiasxl\resources\views\userOptions\settings.blade.php)
Is there anyway to send the parameters with a compact alike or I need to send it through the link? Was avoiding to show the username on the url.
Edit2: For further clarification, this works as intended
<button onclick="window.location='{{url('/settings/' . $user->username)}}'" type="button" id="dadosPessoais" class="btn btn-default">Alterar Dados Pessoais
<i class="glyphicon glyphicon-wrench"></i>
</button>
but I was trying not to send id's and usernames through the URL.
If this is not achievable it's ok, but if there's a way I can't find it, that's why I'm asking
I think you have to add a parameter in the Route and receive the data in the controller function. I'd do something like this:
Route:
Route::get('/callPermissions/{user}', 'SidebarController#callPermissions');
Controller:
public function callPermissions(Request $request, $user)
{
//get data related to $user
}
Ajax call:
$.get('callPermissions/'+userIdVariable, {usernameSend:content, '_token': $('meta[name=csrf-token]').attr('content'),}, function(data){
window.location.replace('settings');
});
This would send the user id through the route.
To get the user id with JavaScript, you can make a hidden field in the Blade file and set the user id as the value. For example, if you using Form helper:
{{ Form::hidden('user_id', $user->id, array('id' => 'js-user-id')) }}
And then, in the JavaScript, you can get the value using something like this:
var userIdVariable = $('#js-user-id')->val();

Get correct index with Splice()

I'm attempting to delete items from my AngularJS view. From the view, I'm passing the index & the ID. In the JS controller, I splice(index) from the AngularJS array/model. And I pass the ID to a $http.get to call a delete to my database. This all works.
....
Until I make a request to refresh my page. Every 5 seconds I make a request to update the Angular model and I concat any new data to it. But what I'm finding is it screws up my index values. I assumed it was reordering my index: and reading this StackOverflow thread helped confirm that.
What would happen is that I push delete for the 3rd item on the page, and it deletes that ID from the DB. But it splices the wrong item from the page until I refresh the page.
How do I make sure that I'm always passing the correct index?
View
<li ng-repeat="new in news | filter:query | orderBy:orderProp">
<div class="newsitem" id="newspost{{new.id}}">
<h4 ng-model="news.title">{{new.title}} </h4>
<p ng-model="news.text">{{new.text}}</p>
<a class="btn btn-info" ng-click="visible = true">View article</a>
<a ng-click="deleteNews(index,new.id)" class="btn btn-danger btn-mini">Delete</a>
</div>
</li>
controllers.js
$scope.deleteNews = function(index, id) {
$http.get('/ci/index.php/news/delete_news_ajax/'+id).success(function(){
$scope.news.splice(index, 1);
});
};
Instead of passing the index and id, pass new:
<a ng-click="deleteNews(new)" ...>
Then use indexOf in your controller function:
$scope.deleteNews = function(newsItem) {
$http.get('/ci/index.php/news/delete_news_ajax/' + newsItem.id)).success(function() {
$scope.news.splice($scope.news.indexOf(newsItem), 1);
});
}

Categories