I created a small site by laravel 6, with the four blade index, create, edit, show and an authentication system, I want everyone to see the blades index and show, and the blades create and edit prohibit that if user authenticate.
TinghirsController.php
public function __construct() {
$this->middleware('auth');
}
public function index()
{
$tinghirs=Tinghir::orderBy('created_at','desc')->paginate(30);
return view('tinghirs.index', ['tinghirs' => $tinghirs]);
}
public function create()
{
return view('tinghirs.create');
}
public function show($id){
$tinghirs = Tinghir::where('id',$id)->firstOrfail();
return view('tinghirs.show', ['tinghirs' => $tinghirs]);
}
public function edit($id) {
$tinghir = Tinghir::find($id);
return view('tinghirs.edit', ['tinghir' => $tinghir]);
}
Route/web.php
Route::resource('tinghirs','TinghirsController');
As per the documentation, you can specify which controller methods you want to apply a piece of middleware to. In you're case you want to apply the auth middleware to all methods except index and show.
To achieve change the middleware call in your __constructor method to be:
$this->middleware('auth')->except('index', 'show');
Related
I'm trying to set up a basic Laravel CRUD application, and I'm getting stuck setting up the pages for each action.
When I visit the route case/create, it opens the page for show instead.
routes/web.php
use App\Http\Controllers\HospitalCase as HospitalCase;
Route::controller(HospitalCase::class)->group(function() {
Route::get('/cases','index')->middleware('auth')->name('cases');
Route::get('/case/{id}','show')->middleware('auth');
Route::get('/case/create','create')->middleware('auth');
Route::post('/case/create','store')->middleware('auth');
Route::get('/case/edit/{$id}','edit')->middleware('auth');
Route::post('/case/edit/{$id}','update')->middleware('auth');
Route::get('/case/delete/{$id}','destroy')->middleware('auth');
});
HospitalCase.php controller
class HospitalCase extends Controller
{
function index()
{
echo 'index';
}
function create()
{
echo 'create';
}
function show($id)
{
echo 'show';
}
function store()
{
// validation rules
}
function edit($id)
{
return view('case/edit');
}
function update($id)
{
}
function destroy($id)
{
}
}
This is what I see on the browser:
I have been trying to figure this out for hours and can't think of what I'm doing wrong.
PS: The auth middleware is using laravel breeze (unmodified)
The reason it's showing the show route is because you defined
Route::get('/case/{id}','show')->middleware('auth');
before it, therefore, it's matching case/create as show('create')
Try defining the route afterwards.
Route::get('/case/create','create')->middleware('auth');
Route::post('/case/create','store')->middleware('auth');
Route::get('/case/{id}','show')->middleware('auth');
Just want to reiterate what #TimLewis has suggested, I think you need to put this route:
Route::get('/case/create','create')->middleware('auth');
Above this route:
Route::get('/case/{id}','show')->middleware('auth');
But you could try using Laravel’s route resource so you don’t need to write out all the routes -
use App\Http\Controllers\HospitalCaseController;
Route::resource('case', HospitalCaseController::class);
Why is it that whenever I redirect something through the constructor of my Codeigniter 4 controller is not working?
<?php namespace App\Controllers\Web\Auth;
class Register extends \App\Controllers\BaseController
{
function __construct()
{
if(session('username')){
return redirect()->to('/dashboard');
}
}
public function index()
{
// return view('welcome_message');
}
}
But if I put it inside index it's working as expected.
public function index()
{
if(session('username')){
return redirect()->to('/dashboard');
}
}
The thing is, I do not want to use it directly inside index because I it need on the other method of the same file.
As per the Codeigniter forum, you can no longer use the redirect method in the constructor to redirect to any of the controllers.
Please refer the below link for more information
https://forum.codeigniter.com/thread-74537.html
It clearly states that redirect() will return a class instance instead of setting a header and you cannot return an instance of another class while instantiating a different class in PHP.
So that's why you can't use redirect method in constructor.
Instead, what I can suggest to you is that use the header method and redirect to your desired controller.
<?php namespace App\Controllers\Web\Auth;
class Register extends \App\Controllers\BaseController
{
function __construct()
{
if(session('username')){
header('Location: /dashboard');
}
}
}
If that's not feasible or difficult to achieve you can follow the below code
<?php namespace App\Controllers\Web\Auth;
class Register extends \App\Controllers\BaseController
{
function __construct()
{
//call to session exists method
$this->is_session_available();
}
private function is_session_available(){
if(session('username')){
return redirect()->to('/dashboard');
}else{
return redirect()->to('/login');
}
}
}
The 2nd solution will be more interactive than the first one. And make sure the method is private. So that it should not be called from other class instances.
The community team has also given a solution to look into the controller filter.
https://codeigniter4.github.io/CodeIgniter4/incoming/filters.html
Please refer to the thread. I hope it may help you in finding a better solution.
In this case you shouldn't even be doing this kind of logic in your controllers. This should be done in a filter and not your controllers.
So you have your controller Register.
You should create a filter in your app/filters folder something like checkLogin.php
That filter should have the following structure:
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class CheckLogin implements FilterInterface
{
/**
* Check loggedIn to redirect page
*/
public function before(RequestInterface $request, $arguments = null)
{
$session = \Config\Services::session();
if (session('username')) {
return redirect()->to('/dashboard');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
}
Then in your app/config/Filters.php your should add the filter to the desired controller.
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'checkLogin' => \App\Filters\CheckLogin::class,
];
// List filter aliases and any before/after uri patterns
public $filters = [
'checkLogin' => ['before' => ['Register']],
];
For more information on filters and how to use then please check the documentation.
https://codeigniter.com/user_guide/incoming/filters.html?highlight=filters
You can then even create filters to your other controllers that would redirect to this one in case the user is not logged in.
Codeigniter 4 using initController() to create constructor.
You can't use redirect() inside __construct() or initController() function.
But you can use $response parameter or $this->response to call redirect in initController() before call another function in controller;
<?php namespace App\Controllers\Web\Auth;
class Register extends \App\Controllers\BaseController
{
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
if(session('username')){
$response->redirect(base_url('dashboard')); // or use $this->response->redirect(base_url('dashboard'));
}
}
public function index()
{
// return view('welcome_message');
}
}
I just got into CI 4 and i had the same issue as you did, since i've been approaching the login system as with CI 3.
So here is the proper way of doing it right. Enjoy.
Codeigniter 4 do not has any return on Constructor, but you can use like this
public function __construct()
{
if (!session()->has('user_id')) {
header('location:/home');
exit();
}
}
Don't forget to use exit()
But, you better use Filters
Simple question but i'm quite new to Laravel.
I've got my middleware function attached to my dish controller at the top, however i want it attached to my dish/create route specifically.
function __construct() {
$this->middleware('auth:restaurantuser');
}
I thought in theory this would work, but it doesn't.
public function create()
{
function __construct() {
$this->middleware('auth:restaurantuser');
}
return view('dishes.create')->with('restaurants', Restaurant::all());
}
Add the middleware in your specific route.
Route::get('dishes/create', 'DishesController#create')->name('dishes.create')->middleware('auth:restaurantuser');
Middleware for Route In Web file:
Route::get('dishes/create', 'DishesController#create')->name('dishes.create')->middleware('auth:restaurantuser');
Remove your middleware from constructor..
public function create()
{
return view('dishes.create')->with('restaurants', Restaurant::all());
}
for more detail go to this link
https://laravel.com/docs/6.x/middleware#assigning-middleware-to-routes
I am using Laravel AdminLTE and I have it all configured, there is just one part I do not understand. I made my route like so:
Route::get('/admin/painlevel', function () {
return view('painlevel');
});
and I have this method in app/Http/Controllers/v1/PainLevelController.php
public function index()
{
return PdTpainlevel::select('pkpainlevel as id', 'painlevel_name as name')->get();
}
How would I call that method and display the data in my painlevel view?
Your current route is merely returning the view('painlevel') directly.
You need to update your route to:
Route::get('/admin/painlevel', 'V1\PainLevelController#index');
In your controller:
public function index()
{
$data = PdTpainlevel::select('pkpainlevel as id', 'painlevel_name as name')->get();
return view('painlevel', compact('data'));
}
You might want to start glancing through the documentations, start with Route, Controller and View
route create like this
Route::get('/administrator', 'administrator\LoginController#index');
and controller create like this
public function index()
{
$data['title']="Admin | DashBoard";
$data['name']="Dilip Singh Shekhawat";
view('administrator/menu_bar',$data);
return view('administrator/dashboard',$data);
}
its working .
how can i use same route for two different controller function methods in laravel
first controller
public function index()
{
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}
second controller
public function index()
{
return view('search.index');
}
i want to use these two different controller functions for one route.
This is my route name
Route::get('/computer', [
'uses' => 'ComputerProductsController#index',
'as' => 'computer.list'
]);
laravel needs somehow to identify which exactly method you want. for example you can pass the parameter, which will identify which method to call.
public function index(Request $request)
{
// if param exists, call function from another controller
if($request->has('callAnotherMethod')){
return app('App\Http\Controllers\yourControllerHere')->index();
}
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}
You can't. If you want to add search functionality to your first controller's index page, you should determine which page to show inside your controller.
A possible example controller:
public function index(Illuminate\Http\Request $request)
{
// If the URL contains a 'search' parameter
// (eg. /computer?search=intel)
if ($request->has('search')) {
// Do some searching here and
// show the search results page
return view('search.index');
}
$comproducts = Comproduct::paginate(6);
$items = Item::orderBy('name')->get();
return view('computer', compact(['comproducts', 'items']));
}