For my app i've created a function that returns either a view or an already rendered view inside some json. Since i will need to use this function quite alot i made a custom helper so i can call it from every controller. however unfortunately, when i try to use another alias inside this helper it does not seem to recognize it. giving me a message that says that the alias 'Request' was not found even though i can access and use it from any controller.
I've added the helper inside de config/app.php with an alias so it's easier to access it.
This is my code:
controller:
use AppHelper;
class MediaController extends Controller
{
public function index()
{
return AppHelper::returnView("backend.media.index", "navigation.media.media");
}
...
AppHelper:
<?php
namespace App\Helpers;
use Request;
class AppHelper
{
public static function returnView($viewName, $menu, $data = []) {
$template = $viewName.'-template';
$view = $viewName;
if (Request::ajax()) {
if(isset($data->id)){
$navigation = view('backend.navigation.right-menu')->with('id', $data->id)->with('menuItems', $menu)->render();
} else {
...
In the helper i've also tried to call the 'Request' via its actual path but to no avail.
I've tried looking up a solution for an hour or so now but just can't seem to find it on google or on stackoverflow.
Thanks for reading.
kind regards, Simon
I don't think
use Request;
is specific enough, considering the number of different Request
classes in Laravel. You're probably looking for:
use Illuminate\Http\Request;
if you want to define Request $request
somewhere in your AppHelper
, or the alias Request
, available via:
use Illuminate\Support\Facades\Request;
Which should allow the use of Request::ajax()
and similar functions.
Alternatively, you could pass the $request
object, which is already available from any controller method, from your MediaController
function index()
, like:
MediaController.php
use Illuminate\Http\Request;
public function index(Request $request){
return AppHelper::returnView($request, "backend.media.index", "navigation.media.media");
}
AppHelper.php
public static function returnView($request, $viewName, $menu, $data = []) {
...
if($request->ajax()){
...
}
}
Edit: Some caveats to the ajax()
method:
use Illuminate\Support\Facades\Request;
...
if(Request::ajax()){ ... }
The above should work fine, or, remove the use
statement and reference with
if(\Request::ajax()){ ... }
When passing the $request
, make sure it is an instance of Illuminate\Http\Request
, and $request->ajax()
should work fine.