How to add a new function to crud controller in Laravel 4? - php

I'm using Resourceful controller which there are default functions such as index, create, store, show, edit, update and destroy. My question is that how can I add my own function to that controller? For instance I add a function in that controller like this:
class Account extends \Eloquent {
.
.
.
/**
* Attempt login.
* GET /accounts/login
*
* #return Response
*/
public function login()
{
//
echo "You are in login page";
}
But it seems not work when i enter that url: account/login. This is my route file:
Route::resource('account', 'AccountsController');

You need to add a separate route for it, and the route needs to come before Laravel generates the routes for the resource controller.
Route::get('account/login', 'AccountsController#login');
Route::resource('account', 'AccountsController');

Related

Prestashop get static token for controler

I am developing a module that has function that need to run periodically in cron.
The idea of implementation is to create a controller that third party cron module is going to call. My problem is that in order to call that controller a token is needed. Tokens in admin panel are temporary per session. Is there any way to get static token for a certain controller? Or is there a better way to implement what I want (through api or something)?
routes.yml:
admin_mymodule_myaction:
path: /mymodule/myaction
methods: [GET]
defaults:
_controller: 'PrestaShop\Module\MyModule\Controller\Admin\MyController::myAction'
MyController.php:
class MyController extends FrameworkBundleAdminController{
public function myAction(){
...
}
}
link to controller (token is temporary):
http://localhost/admin303/index.php/modules/mymodule/myaction?_token=uPmkkqeqBVfnjUGdLKs9_Ik585Q1GlsXWK-qiGfC3r0
I found the solution.
I need to use Front controller, NOT Admin controller. Front controller needs no token, I can define my own security system.
https://devdocs.prestashop.com/1.7/modules/concepts/controllers/front-controllers/#using-a-front-controller-as-a-cron-task
mymodule/controllers/front/cron.php:
<?php
class MyModuleCronModuleFrontController extends ModuleFrontController
{
/** #var bool If set to true, will be redirected to authentication page */
public $auth = false;
/** #var bool */
public $ajax;
public function display()
{
$this->ajax = 1;
//my functionality goes here
$this->ajaxDie("OK.");
}
}
and the link to trigger functionality will be:
http://localhost/index.php?fc=module&module=mymodule&controller=cron
Wonder why official documentation did not come up during Google search.

Auth middleware optional in Laravel

I have my controller ExampleController:
class ExampleController extends Controller
{
function __construct()
{
$this->middleware('auth:student')->only(['store', 'update', 'destroy']);
}
public function index()
{
if(CheckUser::student()) {
dd("Is student");
}
dd("Isn't student");
}
/**
* Another method's not relevant.
**/
}
I'm trying to add some logic if is student.
But have one problem, I just can access: Auth::user() if I set the middleware. But this specific method can be accessed without has logged in.
My question
Is possible to create a not required middleware for what if logged get user information?
Note: I'm using Laravel passport with multi auth.
If you want to protect specific methods that are in your controller and leave out others in the same controller
You may try to protect your endpoint on the routes files (api.php or web.php) rather than on the Constructor
//protected routes
Route::group(['middleware' => 'auth:api'], function () {
Route::post('customer/picture/add', 'Mobile\AuthController#addProfilePicture');
Route::post('customer/phone/update', 'Mobile\AuthController#updatePhoneNumber');
});
//unprotected routes
Route::get('customer/login', 'Mobile\AuthController#getLoginForm');

Laravel 7 redirects to login Page

I have a code in HomeController.php in the Laravel framework, but I could not access the index/homepage it redirects to the login page. what is the blunder I am committing?
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = User::get();
return view('home', compact('users'));
}
public function user($id){
$user = User::find($id);
return view('user', compact('user'));
}
public function ajax(Request $request){
$user = User::find($request->user_id);
$response = auth()->user()->toggleFollow($user);
return response()->json(['success'=> $response]);
}
}
The answer is simple. In the __construct() method, you specified that every function under this controller must use the auth middleware. This will redirect to login page is the user is not logged in.
There are a number of ways to work around this, the first being to remove the __construct entirely. However, this is not so recommended.
Another would be to add an except() function
public function __construct()
{
$this->middleware('auth')->except('index');
}
This will allow the condition to apply anywhere else other than the index function.
Based on the code you posted, the homepage route is protected by the 'auth' middleware, which means users have to login to access the resource page (Home page), so you should first login and then it will direct you to the intended page. If you don't want the page to be protected, then you could either remove the $this->middleware('auth') in your constructor, or you could put the index() function separately in a different Controller file and leave it unprotected
you can also control it in the routes (routes/web.php).
Or as already mentioned with middleware: Assigning Middleware To Routes
Route Group
Use route grouping in your web.php file
This way you can determine middleware for specific routes, you can also use grouping inside route group also
And don't use middleware in controller, use it in web.php so you can have a proper idea that how many routes are using middleware

pass data from login controller to login.blade.php in laravel

I am trying to pass data from login controller to login.blade.php in laravel 6 like I using common header throughout the application so I have to create dynamic title and description. default login controller is something like this
class LoginController extends Controller
{
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Don't know how to pass. please help
Just customize your showLoginForm function provided by laravel as default in your LoginController. see code below
class LoginController extends Controller {
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct() {
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('login', ["data"=> 'this is test data']);
}
}
If you are looking to learn Laravel, I would recommend checking out the guides in their documentation here: https://laravel.com/docs/6.x
Relating to authentication, there is a short guide here that will get you up and running quickly: https://laravel.com/docs/6.x/authentication
You can use the two commands below to setup all of the framework and routing that you need to handle authentication automatically, it will also give you an idea of what to look at if you choose to build your own authentication in future.
composer require laravel/ui --dev
php artisan ui vue --auth
Well, there should have a Trait named AuthenticatesUsers onto the LoginController.php in Laravel 6.x. But somehow we don't see it in the login controller you provided above.
The Trait is located here
vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
However there is a method called showLoginForm(). You can override this method and pass whatever you need to pass in as the following.
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
// Notice the second argument
return view('auth.login', ['key' => 'value']);
}
Hope this would make sense.

Laravel 5, how to run a specific method according to the URL received

In my routes files I have a bunch or routes for testing purposes:
/** testing controllers */
Route::get('viewemail', 'TestController#viewemail');
Route::get('restore', 'TestController#restore');
Route::get('sendemail', 'TestController#send_email');
Route::get('socket', 'TestController#socket');
Route::get('colors', 'TestController#colors');
Route::get('view', 'TestController#view_test');
Route::get('numbers', 'TestController#numbers');
Route::get('ncf', 'TestController#ncf');
Route::get('dates', 'TestController#dates');
Route::get('print', 'TestController#printer');
Route::get('{variable}', 'TestController#execute');
/** End of testing controllers */
I want to eliminate all those routes and simple use the name of the given URL to call and return the method:
I have accomplished that in this way:
Route::get('{variable}', 'TestController#execute');
And in my testing controller:
public function execute($method){
return $this->$method();
}
Basically what I want to know if Laravel has a built in solution to do this, I was reading the documentation but couldn't find any way to accomplish this.
From official documentation:
http://laravel.com/docs/5.1/controllers#implicit-controllers
Laravel allows you to easily define a single route to handle every
action in a controller class. First, define the route using the
Route::controller method. The controller method accepts two
arguments. The first is the base URI the controller handles, while the
second is the class name of the controller:
Route::controller('users', 'UserController');
Next, just add methods to your controller. The method names should begin with the
HTTP verb they respond to followed by the title case version of the
URI:
<?php
namespace App\Http\Controllers;
class UserController extends Controller
{
/**
* Responds to requests to GET /users
*/
public function getIndex()
{
//
}
/**
* Responds to requests to GET /users/show/1
*/
public function getShow($id)
{
//
}
/**
* Responds to requests to GET /users/admin-profile
*/
public function getAdminProfile()
{
//
}
/**
* Responds to requests to POST /users/profile
*/
public function postProfile()
{
//
}
}
As you can see in the example above, index methods will respond to the
root URI handled by the controller, which, in this case, is users.
You could add a route pattern for the endpoints you want to listen for. Route them to a controller action, and then inspect the request:
class TestController extends Controller
{
public function handle(Request $request)
{
$method = $request->segment(1); // Gets first segment of URI
// Do something…
}
}
And in your route service provider:
$router->pattern('{variable}', 'foo|bar|qux|baz');

Categories