redirect too many times laravel - 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.

Related

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

Authorization Using Form Requests in Laravel

Not sure what I am doing wrong here but I am having trouble getting the $id of the post to pass to the form request when checking to see if the person editing owns the post. "Job" would be a job posting. Below is the logic in the JobsRequest.
public function authorize()
{
$job=Job::find($this->id);
if($job->user_id == Auth::user()->id){
return true;
}else{
return false;
}
The above keeps returning as false. The update method in the controller is below
public function update(JobsRequest $request, $id)
{
$job=Job::find($id);
$job_data=$request->all();
$job->update($job_data);
return redirect('/jobs/'.$job->id.'/edit');
}
To grab the id within the FormRequest object, you'd need to use the following...
$id = $this->route('id');
Go to the AuthServiceProvider.php and write
$gate->define('show-product',function($user,$product){
return $user->id==$product->customer_id;
});
Then write your controller
$product= Product::find($id);
Auth::loginUsingId(3);
//Auth::logout();
if(Gate::denies('update',$product)){
App::abort('404','Product Not Found');
}
// $this->authorize('update',$product);
return $product->name;
I think It's working perfectly
Try this, which gets the id from the route parameter.
public function authorize(){
$job_id = $this->route('id');
$job=Job::find($job_id);
$user = $this->user();
if($job->user_id == $user->id) return true;
return false;
}
Thanks for pointing me in the right direction. I got this straight from the docs.. This worked for me.
$jobId = $this->route('jobs');
return Job::where('id', $jobId)
->where('user_id', Auth::id())->exists();

Laravel 5 redirect to previous root after filters

I ran into simple problem but I still can't solve it. At the moment i got middleware which checks user status, if it's 0 middleware redirects user to choose status root. So how do i redirect user to route, after successfully picking status, where he got cought by middleware?
My status check middleware:
if (Auth::user()->status == '0') {
return new RedirectResponse(url('/user/user-status'));
}
return $next($request);
I'm using laravel 5.
Thanks in advance!
Lets look into the option of using Redirect::intended() and Redirect::guest()
The code behind Redirect::intended() is:
public function intended($default, $status = 302, $headers = array(), $secure = null)
{
$path = $this->session->get('url.intended', $default);
$this->session->forget('url.intended');
return $this->to($path, $status, $headers, $secure);
}
The one for Redirect::guest() is :
public function guest($path, $status = 302, $headers = array(), $secure = null)
{
$this->session->put('url.intended', $this->generator->full());
return $this->to($path, $status, $headers, $secure);
}
So basically, this means you can do this:
if (!Auth::user()->status) {
return redirect()->guest('/user/user-status');
}
return $next($request);
Then once the process of setting status is completed, you simply run:
return redirect()->intended();
You have to use the redirect provider. Into this function, Laravel memories the intended path.
if (Auth::user()->status == '0') {
{
\Session::flash('flash_message','Please choose a status.');
return redirect()->guest('/user/user-status');
}
return $next($request);
You can try this:
if (Auth::user()->status == '0') {
return redirect()->guest('/user/user-status');
}
return $next($request);
According to code documentation, redirect()->guest() does this: "Create a new redirect response, while putting the current URL in the session.". Then, in your "user status" page, you can get your intended URL in session with Session::get('url.intended') or return redirect()->intended('default-route-if-not-set');

Delete record error with custom method model laravel

User model
public function take($id){
return $this->find($id);
}
public function kill(){
return $this->delete();
}
Route Error 1
Route::get('delete/{userid}', function($id)
{
$user = new User;
$user->take($id); //result the content of $id
$user->kill();
});
i can't delete record with these route and only show blank page (without error).
Route errror 2
Route::get('delete/{userid}', function($id)
{
User::take($id)->kill();
});
And with above route i get error Non-static method User::take() should not be called statically
But i can delete with this route
Route::get('show/{userid}', function($id)
{
$user = new User;
$user->take($id)->kill();
});
So how to fix Route error 1, if i want to use $user-> without chain take() and kill() ? if it possible
How to fix Route error 2, if i want to use User:: , and why these error happen ?
Thanks in advance.
Try below :
Route::get('show/{$id}', function($id)
{
$user = new User;
$user->find($id)->kill();
});
I think the param accepted has to have the same things that is passed to the closure.

Resources