error when try to open route without parameter in Laravel 9 - laravel

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');
}

Related

Auth::user return null in laravel custom login

Users, roles, permissions have in my project.I have use custom login. I call Auth::user() return null.
How can I fix that?
public function check(LoginRequest $request)
{
$userInfo = User::where('email', '=', $request->email)->first();
if(!$userInfo){
return back()->with('message', 'We do not recognize your email address');
}
if($userInfo){
if(Hash::check($request->password, $userInfo->password)){
$request->session()->put('isUser', $userInfo->id);
$user = User::where('id', '=', session('isUser'))->first();
dd(Auth::user());
// dd($userInfo->roles);
// return redirect('home');
} else {
return back()->with('message', 'Incorrect password');
}
}
}
You need to pass the user instance to Auth::login() like this: Auth::user($user);;

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

redirect too many times laravel

I try to use redirect->action It error too many redirect in my Controller
try {
//If check urL category null
if (is_null($category)){
Log::error("[Front] MenuController#menu : notfound public category ");
//error redirect
return redirect()->action('Front\HomeSlideviewController#index', $url);
}
} catch (\Exception $e) {
return 'error';
}
here is my web.php
Route::get('/{url?}', 'MenuController#menu');
Route::get('/{name?}', 'HomeSlideviewController#index')->name('promotiondetail');
I try to make a fucntion if Url is empty use redirect action
Both of your routes are identical and only the first one is matched.
Please note that, when redirecting to action, Laravel is resolving your action to route anyway, so it is the same as redirecting to route name (which is more bulletproof). By the way, the second parameter should be an array.
return redirect()->action('Front\HomeSlideviewController#index', $url);
To do what you want, you need one catchAll action and return different responses based on your logic:
/**
* #param $string
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function catchAllAction($string)
{
$page = Page::whereHas('translations', function ($query) use ($string) {
$query->where('locale', App::getLocale())->where('slug', $string);
})->first();
if ($page) {
return $this->showPage($page);
}
$news = News::whereHas('translations', function ($query) use ($string) {
$query->where('locale', App::getLocale())->where('slug', $string);
})->first();
if ($news) {
return $this->showSingleNews($news);
}
throw new NotFoundHttpException('This page does not exist');
}
You have route conflict, it will call first route every time.
try to change your route.

In Laravel how do i create a query string?

This will be obvious to someone else
I have a route that works and goes to the correct controller
Route::get('v1/holidays/{country}/{year}/{month}/{official?}',
'retrieveHolidayController#test'
so if i go to
http://example.com/v1/holidays/US/2014/03/01
it will go where I want to go
however I want the link to look like
http://example.com/v1/holidays?country=US&year=2014&month=03&official=01
How can I do this please ?
You redefine your route to
Route::get('v1/holidays', 'retrieveHolidayController#test');
Then in your controller you can get the param values with $request
public function test(Request $request)
{
if ( $request->has('country') && $request->country != '') {
$country = $request->country;
}
if ( $request->has('year') && $request->year != '') {
$year = $request->year;
}
.... // and the others. Then you can query like this
$holidays = Holiday::when($country, function($query) use ($country) {
return $query->where('country', $country);
})
->when($year, function($query) use ($year) {
return $query->where('year', $year);
})
->get();
//Using 'when' only executes the closure if the variable exists
}
Now, you can use your URL just the way you wanted: http://example.com/v1/holidays?country=US&year=2014&month=03&official=01
Make country,year and monthalso optional:-
Route::get('v1/holidays/{country?}/{year?}/{month?}/{official?}', 'retrieveHolidayController#test')
Route::get('v1/holidays', 'retrieveHolidayController#test');
Route::get('v1/holidays/{country}/{year}/{month}/{official?}', function($country){
return redirect()->to(action('retrieveHolidayController#test', ["country"=>$country,......]));
});
access to http://example.com/v1/holidays/US/2014/03/01
redirect to http://example.com/v1/holidays?country=US&year=2014&month=03&offical=01
if official param is null redirect param offical= param is nullable
not feel good
so
isset($official){
$paramArry["official"] = $official;
}

Trying to get property of non-object Laravel Auth

EDIT : I am testing it now, so weird that sometimes it works and sometimes it gives me that error.
I have an application, I've override the logout function in Laravel so I have this in my AuthController.php
public function getLogout()
{
$userid = Auth::user()->id;
date_default_timezone_set('Asia/Taipei');
$today = date('Y-m-d');
$logHour = new LoginHour();
$checkLogin = $logHour->checkLoginHoursOut(intval($userid), $today);
if($checkLogin != null)
{
$loginhours = '';
$timestamp = date('Y-m-d h:i:s');
$timestamp2 = strtotime($timestamp);
$userLastLogin = $checkLogin[0]->timestamp;
$userLastLogin2 = strtotime($userLastLogin);
// Get difference in hours
$diffHours = round(($timestamp2 - $userLastLogin2) / 3600, 2);
LoginHour::where('date', '=', $today)->
where('user_id', '=', $userid)->
update(['loginhours' => $checkLogin[0]->loginhours + $diffHours, 'status' => 0, 'timestamp' => $timestamp]);
}
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/auth/login');
}
But for some reason when I am trying to logout I have this error:
Trying to get property of non-object
Which points me to this line
$userid = Auth::user()->id;
What could be the problem? I believe I could still access the Auth coz I'm not yet calling the Auth::logout(); before that line?
I guess that the problem exists when you visit the logout route, without a logged in user.
So, you should check it at the top.
public function getLogout()
{
if (Auth::guest()) return;
...
}

Resources