Laravel - Request::server('HTTP_HOST') returns 'localhost' from within a helper class - session

I want to get the current domain, using Request::server('HTTP_HOST') - however when I call this from within a helper class it comes back as 'localhost' which is not what I want. From a controller it works as expected. Is there a way to access this information from within a helper class?
The helper class looks like this:
class ApiWrapper {
public static function call($model, $method='', array $input) {
$domain = Request::server('HTTP_HOST');
}
}

You can do URL::to('/') to get the base URL of the Laravel application, if that's what you're asking for. If doing Request::server('HTTP_HOST') from your controller is giving you the desired result, doing the same from the helper class shouldn't be any different.

Related

How to call method dynamically on routes on Laravel?

I'm a newbie with this and I need some help.
I'm developing some kind of music library and let's say I don't want to make a route for each artist so I have made this one:
Route::get('/{artist_name}', 'Artist_controller#{artist_name}');
I get the value of {artist_name} from my view and the route works, for instance, the artist_name may be John and the url generated is localhost:8000/John. But when it comes to look for the class in the controller it doesn't work. I have a class named John in my controller, but I keep getting this error when I try to access:
BadMethodCallException
Method [{artist_name}] does not exist.
So I guess the route isn't taking the value of {artist_name}. What I intend is the route to be processed like:
Route::get('/John', 'Artist_controller#John');
But as I said, I don't want to create a specific route for an artist.
I'd appreciate any kind of help. Thank You
There is no need to create a dynamic method for each artist. You could have one generic method in your controller that handles retrieving the proper artist information from the database and pass it to the view.
routes file:
Route::get('artists/{artist_id}', 'ArtistsController#show');
ArtistsController.php
class ArtistsController extends Controller
{
public function show($artist_id)
{
$artist = Artists::find($artist_id);
return view('artists.show', ['artist' => $artist]);
}
}
So if the user hits the following URL http://localhost/artists/4 the artist id of 4 will be passed to the show method and it will dynamically looks for an artist with that ID and pass an object of artist to your view.
Of course you are not limited to IDs in your URLs. You can use the name if it was unique and your code will be as the following.
routes file:
Route::get('artists/{artist_name}', 'ArtistsController#show');
ArtistsController.php
class ArtistsController extends Controller
{
public function show($artist_name)
{
$artist = Artist::where('name', $artist_name);
return view('artists.show', ['artist' => $artist]);
}
}
I suggest you read this documentation for more information about routing.
You can not have dynamic method (controller action) in a controller class. Instead you should define a method and pass the route parameter to that action.
In your route (web.php) file:
Route::get('/{artist_name}', 'ArtistController#artist');
then in ArtistController.php:
public function artist ($artist_name) {
// do stuff based on $artist_name
}
To get more info read these 2 documentation pages. Controller and Routing.

Laravel: Grab data from the Controller from inside a view composer

Atm I'm creating this view composer for fun. It is collecting .js filenames and then passing it to the layout to be linked. The filenames used depend on the current page. For example a lower ranked page like Slides, doesn't include ajax requests used in UserManagement. Please don't ask me why I would do this xD. Im planning to validate requests anyway. Just being bored.
Anyways, as I'm quite new to laravel I'm still looking for more efficient ways to do things.
Atm Im accessing the file names staticly. The Controller now looks like this
class Controller extends BaseController
{
public static $js_file_names = [];
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
In the pagecontroller I construct the filenames:
class SlidesController extends Controller
{
public function __construct()
{
parent::$js_file_names = ['ccs', 'ajax-updates'];
}
And finaly I retreive them inside the registered Viewcomposer like this:
(during development $use_filenames has all files as default)
public function __construct()
{
$filenames = Controller::$js_file_names;
if( !empty($filenames) )
$this->use_filenames = $filenames;
var_dump($this->use_filenames);die;
}
It all seems to be working fine, but the big question is, is there a better way to access controller data from inside a viewcomposer? Every time I try to google this, I get results like 'passing data to views' etc, which is not rly the problem.
Update:
Another idea I had is to store all the filenames to be used in an array inside the viewcomposer itself, and check if the current page exists in that array. This would keep the controllers cleaner.
Using a view composer doesn't really make sense in this situation. Since your controllers already 'know' which files they intent to share, you may as well just pass them to the view like so:
class SlidesController extends Controller
{
public function __construct()
{
View::share('user_filenames', ['ccs', 'ajax-updates']);
}
}
A composer is more for sharing concrete elements such as collections of users, a service provider or some other class instance, for example.

How to autoload custom class in Laravel?

I wrote custom class with method that returns array.
I need to autoload this class like Auth() class in Laravel, that I could get access to it from any controller not using use
Create one custom helper file
and add function
if (! function_exists('yourcustomclass')) {
function yourcustomclass()
{
use App\Http\yourcustomclassname;
return new yourcustomclassname()
}
}
you can use yourcustomclass() function from anywhere to get yourcustomclassname class object
When accessing class/function from other namespace than you're currently in you have to use Fully-Qualified Class Name (or type use, but you don't want to do that), so instead of Auth::user() you need to write \Auth::user()
\ at the beginning means that class is located in root namespace
Why don't you write super method(s) in App\Http\Controllers\Controller?
Simply call super method(s) in the subclass which extends Controller

How to Call a controller function in another Controller in Laravel 5

im using laravel 5.
I need to call a controller function but this should be done in another controller.
I dont know how to do this
public function examplefunction(){
//stuff
}
And i have a Route for this function, so at
public function otherfunctioninothercontroller(){
// I need examplefunction here
}
how Can i do this?
1) First way
use App\Http\Controllers\OtherController;
class TestController extends Controller
{
public function index()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
2) Second way
app('App\Http\Controllers\OtherController')->method();
Both way you can get another controller function.
If they are not in the same folder, place use namespace\to\ExampleClass; on top of your file, then you are able to instantiate your controller.
You can simply instantiate the controller and call the desired method as follows
FirstController.php:
namespace App\Http\Controllers;
class FirstController extends Controller {
public function examplefunction() {
// TODO: implement functionality
}
}
SecondController.php:
namespace App\Http\Controllers;
class SecondController extends Controller {
public function test() {
$object = new FirstController();
$object->examplefunction();
}
}
Now, after i've answered the question, i would like to add the following comment:
Controllers are classes, all rules that applies to normal classes can be applied to them
However, instantiating a controller directly inside another controller to call a desired method signifies a problem in your design for the following 2 reasons:
A controller cannot obtain an instance of another controller directly
Controller should contain as little business logic as possible, and if possible none
The closest possible solution to what you want (WITHOUT BREAKING MVC) is to make an HTTP request to the route that points to the desired method (using cURL, for example) and read the response as the returned data
But this still doesn't make much sense in this scenario because after all you're making an HTTP request from a method in a controller in your project on your server to a method in a controller in your project on your server, seems like unnecessary overhead, right ?
As i said earlier, a controller should contain as little business logic as possible because the logic should stay inside specialized classes (commonly known as Service Classes), and when a processing is requested the controller simply delegates the job of processing to the appropriate service class which does the processing and returns the results to the controller which in turn sends it back as a response
Now imagine if you've the following scenario:
We've got an application that consists of 3 functionalities:
A user can register an account from web application
There's a mobile application that talks to an API to register a user
There's an admin panel, which he can use to add new user
Obviously you need to create 3 controllers, but those controllers contains repeated logic, would you copy/paste the code everywhere ?
Why not encapsulate this logic inside a service class and call it from the controller when needed ?
Let's say I have Controller1 and Controller2. I want to call a function of Controller1 from inside a function placed in Controller2.
// Controller1.php
class Controller1 {
public static function f1()
{
}
}
And on the other controller:
// Controller2.php
use App\Http\Controllers\Controller1;
class Controller2 {
public function f2()
{
return Controller1::f1();
}
}
Points to be noted:
f1() is declared static
A call to a controller from inside another controller is a bad idea. There is no sense of meaning of controllers then. You should just redirect to web.php to save safe whole architecture like this:
class MyController {
public function aSwitchCaseFunction(Request $requestPrm){
...
//getting path string from request here
...
switch($myCase){
case CASE_1:
return redirect()->route('/a/route/path');
....
}
}
}

how to debug data query in laravel

This is a beginner question, but I searched for an hour and couldn't find an answer.
I am trying to write a simple data query which I included in my HomeController
<?php
class HomeController extends BaseController {
public function showWelcome()
{
return View::make('hello');
}
}
$programs=DB::table('node')->where('type', 'Programs')->get();
$programs is undefined so I am guessing that my query didn't work but I have no idea how to debug it. I tried installing firebug and phpbug and chromphp tools but they don't seem to show anything. My apache log doesn't show anything either. Am I missing something? How do I debug this?
You can't use an expression outside of a method when using a class, instead you need to put it inside a method like:
class HomeController extends BaseController {
public function getPrograms()
{
$programs = DB::table('node')->where('type', 'Programs')->get();
// pass the $programs to the programs view for showing it
return View::make('programs')->with('programs', $programs);
}
}
So, for example, if you have a route like this:
Route::get('/programs', 'HomeController#getPrograms');
Then you may use an URL like: example.com/programs to invoke the getPrograms method in the class HomeController.
Probably this answer doesn't help much but I think you should learn the basics (PHP Manual) first so read books and articles online and check the Laravel website to read the documentation.
You can pass the result of that query to the view like so:
class HomeController extends BaseController {
public function showWelcome()
{
$programs = DB::table('node')->where('type', 'Programs')->get();
return View::make('hello', array('programs' => $programs));
}
}
And in your view you will have access to the $programs variable.
I don't know If i'm missing the point, but can't you use the "dd($programs)" to check what is or not is inside the variable?

Resources