Laravel 6 - My Route doesnt work in Resource Controller - laravel

I have a Admincontroller. Here I can do a simple CRUD function.
With this route: Route::resource('admin', 'AdminController');
Everything (create, edit destroy) works perfect.
Now I have a new function in this Controller.
Named deactivate. Here i can deactivate users.
this is the function:
public function deactivate($id)
{
$user = User::find($id);
if ($user->verified == 1){
$user->verified = 0;
$user->save();
$angebot = Angebot::where('firma', $id);
$angebot->delete();
return redirect('/admin')->with('success', 'Nutzer wurde erfolgreich deaktiviert');
}
if($user->verified == 0){
$user->verified = 1;
$user->save();
return redirect('/admin')->with('success', 'Nutzer wurde erfolgreich aktiviert');
}
}
for this function i have this route:
Route::get('admin/{id}', 'AdminController#deactivate')->name('admin.deactivate');
in my view it looks like this:
<a href="{{ route('admin.deactivate',$user->id)}}">
if i click on this link it goes to /admin/2 (so it gives me the right id)
but it doesnt redirekt to /admin so i think the route doesnt work because the function should work
does anyone know why?
is it because i do this in my ressource controller?

When you want to add an extra route to your resource route,add it above the resource route..
Route::get('admin/{id}', 'AdminController#deactivate')->name('admin.deactivate');
Route::resource('admin', 'AdminController');

Related

error when try to open route without parameter in Laravel 9

I have a problem when trying to access any route without parameter:
When I wrte any route without {uname} parameter like this or any other one:
http://127.0.0.1:8000/login/
show me this error :
and it is in the home in another controller?
These is my routes:
Route::get('/{uname?}', [HomeController::class, 'home'])->name('home');
Route::get('/info/{uname?}', [HomeController::class, 'info'])->name('info.me');
Route::get('/skills/{uname?}', [HomeController::class, 'skills'])->name('skills');
Route::get('/education/{uname?}', [HomeController::class, 'education'])->name('education');
Route::get('/achievements/{uname?}', [HomeController::class, 'achievements'])->name('achievements');
Route::get('/services/{uname?}', [HomeController::class, 'services'])->name('services');
Route::get('/contact/{uname?}', [HomeController::class, 'contact'])->name('contact');
Route::post('/send-email', [HomeController::class, 'sendEmail'])->name('send-email');
Route::get('/dashboard/index', [DashboardController::class, 'index'])->name('dashboard.index');
Route::resource('/dashboard/about', AboutController::class);
Route::resource('/dashboard/skills', SkillsController::class);
Route::resource('/dashboard/education', EducationController::class);
and here is my HomeController:
class HomeController extends Controller
{
function home($uname) {
$user = User::where('name', '=', $uname)->first();
$about = $user->about;
return view('home', compact('user', 'about'));
}
function info($uname) {
$user = User::where('name', '=', $uname)->first();
$about = $user->about;
return view('info', compact(['user', 'about']));
}
function skills($uname) {
$user = User::where('name', '=', $uname)->first();
$about = $user->about;
$skills = $user->skills;
return view('skills', compact(['skills', 'user', 'about']));
}
I have already tried those and nothing changed:
PHP artisan route: cache
PHP artisan cache:clear
Your home route is a catch-all route as you have an optional parameter right after your first dash (/). This will always catch first and stop any other routes from running because it will always match your current url. To solve this you need to put this kind of route as your last route.
As for your error it's because your not finding any user. If ->first() doesn't find a matching row it will return null, and if it's null you will get an error if you're treating it as an object. You either need to check if $user is null and set $about based on that or use firstOrFail and then create a response for that error.
Your error on line 13 of HomeController...
can't find user with your condition and return null and you in line 14 want get about from null....
you have to choose :
1 :
function home($uname) {
$user = User::where('name', '=', $uname)->first();
$about = $user->about ?? null ;
return view('home', compact('user', 'about'));
}
2:
function home($uname) {
$user=$about=null;
if(isset($uname)){
$user = User::where('name', '=', $uname)->first();
$about = $user->about ?? null ;
}
return view('home', compact('user', 'about'));
}
also you can change first() to firstOrFaill() in first method to get 404 page
$uname is an optional parameter. When it's not available no user could be found. You should check if $user is not null and return an error page or something like that, when $user is null.
if ($user !== null) {
$about = $user->about;
return view('home', compact('user', 'about'));
} else {
return view('error');
}

Authorization isn’t executed in laravel

This is form ‘login’, when I’m enter information in input and after press button ‘login’ I move to page with audit where 0 is authorization isn't executed and 1 is authorization is executed. I'm trying to create authorization in laravel.
I did it in other project in order to understand how it works and then all was good. Now I'm trying to transfer it in my main project but when I am logging in nothing work.
I don't have any mistake, authorization is simply not executed. I will grateful for any help.
Registration function
public function sub(ContactSignup $request){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
$contact = new SignUps();
$contact->name = $request->name;
$contact->surname = $request->surname;
$contact->age = $request->age;
$contact->password = bcrypt($request->password);
$contact->email = $request->email;
$contact->save();
Auth::login($contact);
if($contact){
Auth::login($contact);
return redirect(route('user.sign-up'))->with('success', 'Реєстрація пройшла успішно');
}
}
Function login
public function subin(ContactSignin $request){
if(Auth::check()){
return redirect()->intended(route('user.mainpage'));
}
$contact = $request->only(['email', 'password']);
if(Auth::attempt($contact)) {
dd(1);
}
else {
dd(0);
}
return redirect()->intended(route('user.mainpage'));
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return redirect()->route('mainpage');
});
Route::name('user.')->group(function(){
Route::view('mainpage', 'mainpage')->middleware('auth')->name('mainpage');
Route::get('/signin', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signin');
})->name('sign-in');
Route::post('/signin', [\App\Http\Controllers\ContactController::class, 'subin'])->name('sign-in');
Route::get('logout', function(){
Auth::logout();
return redirect('/');
})->name('logout');
Route::get('/signup', function(){
if(Auth::check()){
return redirect(route('user.mainpage'));
}
return view('signup');
})->name('sign-up');
Route::post('/signup', [\App\Http\Controllers\ContactController::class, 'sub'])->name('sign-up');
});
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
in your methods inside your controller you have form request class called ContactSignin
in this class you have code
public function authorize()
{
return false;
}
make it true
The form request class is responsible of validating your request ,
also contains an authorize method. Within this method, you may determine if the authenticated user actually has the authority to update a given resource
since you handle authorization logic for the request in the routes by provide
middleware('auth') it is no need to check for use authentication in your form request class
first you don't have route named ('user.mainpage') you have to define it in web.php
second , since you named your rout in
Route::get('/mainpage', function () {
return view('mainpage');
})->name('mainpage');
, you must redirect to the name of the route not to the path
for example if your route is ('/api/main')->name('main') , you have to put the rout name in the redirect method , for example redirect(route('main'));

How to redirect excluding some slug in laravel routing?

I would like to exclude the {user} in slug route
I want to make:
from example.com/user/someslugs
to exclude the {user} in slug route example.com/someslugs
// This my Verify Controller
class VerifyController extends Controller{
public function redirect($user, $slug){
// Get verify
$verify = Verify::slug($slug)->first();
// Check if verify exists
if (!$verify) {
abort(404);
}
// Redirect to url
return redirect($verify->url);
}
}
Function
// MyFunc
if (!function_exists('verify')) {
function verify($uri, $user){
$model = new \App\Models\Verify;
if (!validate_url($uri)) {
return false;
}
$createVerify = function($url) use ($model){
$slug = \Str::random(6);
$new = $model;
$new->url = $url;
$new->slug = $slug;
$new->save();
return $slug;
};
$route = function($slug, $user){
return route('verify', ['user' => $user, 'slug' => $slug]);
};
if (!$verify = $model->url($uri)->first()) {
$slug = $createVerify($uri);
return $route($slug, $user);
}
return $route($verify->slug, $user);
}
}
Route web.php
// MyRouteVerify
Route::get('{user}/{slug}', 'VerifyController#redirect')->name('verify');
The main problem when I remove {user} from route and wrong controller is called.
How can I achieve this? to get the full URL exclude the {user}, (example.com/someslugs)?
Any suggestion? And I would really appreciate some good and relative answer. Thanks!
in case you guarantee that your slug will never match your route, you can put your user route at the end of the web.php file
Example
// route list here
Route::get('/someroute', 'SomeController#somemethod');
// the last route in your web.php file
Route::get('/{slug}', 'VerifyController#redirect')->name('verify');
I hope it's useful

My Laravel Routing doesnt work anymore, it shows 404

I have an adminmodul, where I can edit or delete some user profiles and i can activate or deactivate an user profile.
Everything works perfect. But suddenly my routes doesnt work anymore. Now I got the error 404 - page not found.
I dont know what the problem is, because I dont change anything in the code.
I think my routes doesnt working. Does anyone know why?
I tried to change my routes.
<?php
Route::get('/', 'AdminController#index');
Route::get('/{id}',[
'as' => 'adminmodul.deactivate',
'uses' => 'AdminController#deactivate'
]);
Route::resource('/adminmodul', 'AdminController');
Route::get('/{id}/edit', 'AdminController#edit')->name('adminmodul.edit');
this is my web.php
i have a AdminController.php where I have methods: index, create(dont use this), edit, update, destroy and deactivate
for example:
public function destroy($id)
{
$user = User::find($id);
$angebot = Angebot::where('firma', $id);
$angebot->delete();
$user->delete();
return redirect('/')->with('success', 'Nutzer wurde erfolgreich gelöscht');
}
public function deactivate($id)
{
$user = User::find($id);
if ($user->verified == 1){
$user->verified = 0;
$user->save();
$angebot = Angebot::where('firma', $id);
$angebot->delete();
return redirect('/')->with('success', 'Nutzer wurde erfolgreich deaktiviert');
}
if($user->verified == 0){
$user->verified = 1;
$user->save();
return redirect('/')->with('success', 'Nutzer wurde erfolgreich aktiviert');
}
}
the index page is working. My views are located in resources/views/adminmodul and then, create.blade.php, edit.blade.php, show.blade.php and index.blade.php
if i hover over the Link, it shows me the right link /1/edit but if I click on this link it goes to /edit
i tried this:
public function test()
{
return 'test';
}
Route::get('/test', 'AdminController#test');
but it doesnt work either and shows me 404
Why do I get 404 page not found?
I think because of wildcards you should try this order to avoid conflict
Route::get('/', 'AdminController#index');
Route::get('/{id}/edit', 'AdminController#edit')->name('adminmodul.edit');
Route::get('/{id}',[
'as' => 'adminmodul.deactivate',
'uses' => 'AdminController#deactivate'
]);
Route::resource('/adminmodul', 'AdminController');
Put your edit route above Route::resource
Route::get('/{id}/edit', 'AdminController#edit')->name('adminmodul.edit');
Route::resource('/adminmodul', 'AdminController');
Note that your new methods have to go above the Route::resource

Laravel redirect to another page 401 Unauthorized

I have a users table , and have data and this data if clicked its redirect to another page , this page is data from users->id .and its my Controller:
public function indexDataTables_nonpns()
{
$users = User::with('master_agama','master_unit_kerja')->whereNotIn('roles_id',['2','3'])->get();
return Datatables::of($users)->addIndexColumn()
->addColumn('Nama', function ($users) {
return '<a href="/project/non_pns/'.$users->id.'" target="_blank" >'.$users->nama.'</a>';
})
->rawColumns(['Nama' => 'Nama'])
->make(true);
}
this data will redirect to
**return '<#a href="/project/non_pns/'.$users->id.'" target="_blank" >'.$users->nama.'</a>';**
and its controller to showing page :
public function show($id)
{
$users = User::findOrFail($id);
if (!$users)
abort(404);
$keluarga = Data_Keluarga::where('user_id',$id)->get();
$pendidikan = Data_riwayat_pendidikan::where('user_id',$id)->get();
$pelatihan = Master_seminar_pelatihan::where('user_id',$id)->get();
//dd($pelatihan);
return view('admin.profile', ['users' => $users ,'keluarga'=> $keluarga,'pendidikan'=> $pendidikan
,'pelatihan' => $pelatihan
]);
}
and its this route :
Route::get('project/non_pns/{id}', 'AdminController#show')->name('show');
Route::get('/profile', 'AdminController#profile')->name('profiles');
but this if clicked this button , its 401
Unauthorized , You Dont Have Access For This Page
i dont know , i just cleared/delete all data in database , and its make this route get error . please help
At the end of your function use bellow code
public function insert(){
//your code
return redirect('store');
}
if you want to pass id in redirect
public function insert(){
$id=2;
return redirect('store/'.$id);
}

Resources