R
R
Radiss2019-05-06 00:19:10
Laravel
Radiss, 2019-05-06 00:19:10

Why does the redirect not work and messages are not displayed?

I use version 5.2
There are 2 controllers and 2 forms. For a user with id 6 with Admin rights, adding and editing records works, records are saved and edited in the database, but there are no redirects and messages about adding, updates. Also no messages

return redirect()->back()->with(['message'=>'У Вас нет прав']);

If you log in as a user without access rights. Instead, on the site/admin/add/post/17 route:
"Sorry, the page you are looking for could not be found."
1/1 NotFoundHttpException in RouteCollection.php line 161
AdminPostController
spoiler
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;

class AdminPostController extends Controller
{
    public function show()
    {
        return view('default.add_post',['title' => 'Новый материал']);
    }
  
    public function create(Request $request) {
    	if(\Gate::denies('add-article')) {
      return redirect()->back()->with(['message'=>'У Вас нет прав']);
    }

    	$this->validate($request,[
    		'name'=>'required'
    	]);
    	
    	$user = \Auth::user();
    	$data = $request->all();
    	
    	$res = $user->articles()->create([
            'name' => $data['name'],
            'img' => $data['img'],
            'text' => $data['text']
        ]);

        return redirect()->back()->with('message','Материал добавлен');
  }
}


AdminUpdatePostController
spoiler
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Article;

class AdminUpdatePostController extends Controller
{
    public function show(Request $request, $id) {
    	$article = Article::find($id);
    return view('default.update_post',['title' => 'Редактирование материала','article' => $article]);
  }
  
    public function create(Request $request) {
    	$this->validate($request,[
    		'name'=>'required'
    	]);
    	
    	$user = \Auth::user();
    	$data = $request->except('_token');
    	$article = Article::find($data['id']);
    	
    	if(\Gate::allows('update-article',$article)) {
            $article->name = $data['name'];
            $article->img = $data['img'];
            $article->text = $data['text'];
            $res = $user->articles()->save($article);    

            return redirect()->back()->with('message','Материал обновлен');
        }
    	
        return redirect()->back()->with(['message'=>'У Вас нет прав']);
  }
}


AuthServiceProviders
spoiler
namespace App\Providers;

use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\User;

class AuthServiceProvider extends ServiceProvider
{
    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);
        
        //$gate->define('add-article',[email protected]);
        $gate->define('add-article',function(User $user) {        	
        	foreach($user->roles as $role) {
        if($role->name == 'Admin') {
          return TRUE;
        }
      }
        	
        	return FALSE;//FALSE        	
        });
        
        $gate->define('update-article', function (User $user, $article) {	
        	foreach($user->roles as $role) {
        if($role->name == 'Admin') {
          if($user->id == $article->user_id) {
            return TRUE;
          }
        }
      }
      
      return FALSE;
        });
    }
}


route.php
spoiler
Route::group(['middleware' => 'web'], function () {
    Route::auth();
});

//Route::auth();
// admin/edit/post
Route::group(['prefix'=>'admin','middleware'=>['web','auth']],function() {
  // admin/
  Route::get('/',['uses'=>'Admin\[email protected]','as'=>'admin_index']);
  Route::get('/add/post',['uses'=>'Admin\[email protected]','as'=>'admin_add_post']);
  Route::post('/add/post',['uses'=>'Admin\[email protected]','as'=>'admin_add_post_p']);
  Route::get('/update/post/{id}',['uses'=>'Admin\[email protected]','as'=>'admin_add_post']);
  Route::post('/update/post',['uses'=>'Admin\[email protected]','as'=>'admin_update_post_p']);
});


form add_post.blade
spoiler
@extends('default.layouts.layout')

@section('content')

<div class="col-md-9">
  <div class="">
    <h2>Добавление нового материала</h2>
    </div>
  
  @if (count($errors) > 0)
      <div class="alert alert-danger">
          <ul>
              @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
              @endforeach
          </ul>
      </div>
  @endif

  @if (session('message'))
      <div class="alert alert-success">
          {{ session('message') }}
      </div>
  @endif
  
  <form method="post" action="{{ route('admin_add_post_p') }}">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="form-group">
      <label for="name">Заголовок</label>
      <input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Заголовок">
    </div>
    <div class="form-group">
      <label for="img">Изображение</label>
      <input type="text" class="form-control" id="img" value="{{ old('img') }}" name="img" placeholder="img">
    </div>
    <div class="form-group">
      <label for="text">Text</label>
      <textarea class="form-control" id="text" name="text" rows="3">{{ old('text') }}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>	
@endsection


update_post_blade form
spoiler
@extends('default.layouts.layout')

@section('content')

<div class="col-md-9">
  <div class="">
    <h2>Редактирование материала</h2>
    </div>
  
  @if (count($errors) > 0)
      <div class="alert alert-danger">
          <ul>
              @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
              @endforeach
          </ul>
      </div>
  @endif

  @if (session('message'))
      <div class="alert alert-success">
          {{ session('message') }}
      </div>
  @endif
  
  <form method="post" action="{{ route('admin_update_post_p') }}">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
  <input type="hidden" name="id" value="{{ $article->id }}">
    <div class="form-group">
      <label for="name">Заголовок</label>
      <input type="text" class="form-control" id="name" name="name" value="{{ $article->name }}" placeholder="Заголовок">
    </div>
    <div class="form-group">
      <label for="img">Изображение</label>
      <input type="text" class="form-control" id="img" value="{{ $article->img }}" name="img" placeholder="img">
    </div>
    <div class="form-group">
      <label for="text">Text</label>
      <textarea class="form-control" id="text" name="text" rows="3">{{ $article->text }}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>	
@endsection


Kernel.php
spoiler
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
      //  \Illuminate\Session\Middleware\StartSession::class,
      //   \Illuminate\View\Middleware\ShareErrorsFromSession::class
        //\App\Http\Middleware\Mymiddleware::class
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
         'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'mymiddle'=> \App\Http\Middleware\Mymiddleware::class
    ];
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Biocoder, 2019-05-12
@radiss

but redirect and add messages, no updates

And instead of a redirect, then what, an empty page?
If, nevertheless, it redirects to the template you need (in your case, add_post.blade and update_post_blade) and does not display the "message" message that you transmit through the session, then it may be worth checking the settings of the session itself on the server https://laravel.com/docs/ 5.2/session
If you log in as a user without access rights. Instead, on the site/admin/add/post/17 route:
"Sorry, the page you are looking for could not be found."
1/1 NotFoundHttpException in RouteCollection.php line 161
It says right in the log that the page was not found, you don't have such a route "/admin/add/post/{id}", but there is "/admin/add/post" (GET, POST)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question