How to pass Request object from route in Laravel? - laravel-5

Following is my routes where I am calling my Controller directly in route.
How can I pass Request $request to my getBlog Function.. Or is there any way to directly get $request object in my getblog function of controller ???
$artObj = App::make('App\Http\Controllers\Front\ArticleController');
return $artObj->getBlog($id);
Code in Routes:
Route::get('/{slug}', function($slug) {
// Get Id and Type depending on url
$resultarray = App\Model\UrlAlias::getTypefromUrl($slug);
if(!empty($resultarray)) {
if($resultarray[0]['type'] == 'article') {
$id = $resultarray[0]['ref_id'] ;
$artObj = App::make('App\Http\Controllers\Front\ArticleController');
return $artObj->getBlog($id);
} else {
return Response::view("errors.404", $msg, 400);
}
} else {
return Response::view("errors.404", array(), 400);
}
});

You can do in the head of the routes.php file:
use Illuminate\Http\Request;
And then in the beginning of your route:
Route::get('/{slug}', function($slug, Request $request) {
And the $request will be available to you. But that is extremely bad practice. What you should do - is move the whole logic into the controller like that:
Route::group(['namespace' => 'Front'], function(){
Route::get('/{slug}', 'ArticleController#methodName');
});
and then you can use the Request class in your controller class and the controller method:
<?php
namespace App\Http\Controllers\Front
use Illuminate\Http\Request;
class ArticleController
{ ...
public function methodName(Request $request){
...function implementation...
}
...
}

The Request is a global variable, you can access it anywhere with either php code or even some helper Laravel functions.
Just use request() and it's the same as passing the request as an object inside a variable through a function. (It's equivalent to the Request $request variable received).
It improved readability also. Just remember you can't change request objects directly, you'd better use request()->merge(['key' => 'newValue']);

Related

How to pass a parameter to a laravel controller from redirect within the same controller

How do I pass a true false value to the controller from the redirect in the class and to the router and back to another function in the same controller class if that makes sense
Like
public function 1() {
return redirect('route2');
}
public function2() {
I need to access the variable here that some how gets passed from the first function
}
Because these functions are both on my main controller and I need to pass a variable through the route
and back into the controller or is there a way to put a state variable on the class or something I just need to call a function on the controller with conditions from the previous controller function that called called the redirect route.
Also sorry if I am mixing up class and function I am new to laravel and MVC in general.
You can do something like this:
public function first() {
return redirect()->action(
[YourController::class, 'second'], ['value' => true]
);
}
public function second($value = null) {
// whatever you want
}
https://laravel.com/docs/9.x/redirects#redirecting-controller-actions
I think this code help you:
public function 1() {
return to_route('YOUR_ROUTE_NAME', ['value' => 'some things...']);
}
public function2(Request $request, $value) {
// Use the value passed as a route parameter
// $value is 'some things...'
}

Trigger JSON response via Trait in Controller Larael

I'm using Laravel 8 to build an API, I have a route which for the purposes of the question is... /api/fact which GETs a random fact. I have a FactsController.php file and two traits, one for constructing a JSON response, the other for getting a fact. For some reason when calling the trait's function from within my controller (which made the request) I'm not getting any returned JSON back in Postman...
Traits/GetFact.php
<?php
namespace App\Traits;
use App\Traits\ApiResponse;
trait GetFact {
use ApiResponse;
/**
* Get random fact
*
* get random fact
*/
public function getRandomFact () {
$this->getFact();
$this->apiResponse([
'msg' => "Fact..."
], 200, true);
}
}
Traits/ApiResponse.php
<?php
namespace App\Traits;
trait ApiResponse {
/**
* API Response
*
* Return a JSON response for our API with params
*/
public function apiResponse ($data, $code, $success = false) {
return response()->json(array_merge(['success' => $success], $data), $code);
}
}
Controllers/FactController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Traits\GetFact;
class FactsController extends Controller
{
use GetFact;
/**
* Fact
*
* #param Request $request
*/
public function fact()
{
$this->getRandomFact()
}
}
When I make my request to /api/fact I should be getting the returned JSON listed where I'm calling $this->apiResponse() with the msg, but I'm not? It's like the return doesn't seem to return JSON because it's scoped to the trait and not the controller and that there isn't a return in there? How can I achieve the listed.
You are not "returning" anything from your Controller method. You have to return something for their to be a response with content. Also, fact and getRandomFact do not return anything so calling those isn't doing anything for you. You are also calling a getFact method and not assigning the return to anything (if it even returns anything).

How can I redirect from a controller with a value to another controller in laravel?

OrderController.php
if (request('payment_method') == 'online') {
return redirect(route('payments.pay', $order->id));
}
web.php
Route::POST('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');
PublicSslCommerzPaymentController.php
session_start();
class PublicSslCommerzPaymentController extends Controller
{
public function index(Request $request, $ordId)
{
//code...
}
}
Here in index function I need the order id from `OrderController.
But the Error I am getting
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
if you want to redirect to named route you can use this:
return redirect()->route('payments.pay', ['orderId' => $order->id]);
if you want generate redirect to controller action you can try this:
return redirect()->action(
'PublicSslCommerzPaymentController#index', ['ordId' => $order->id]]
);
Just change in your web.php from POST method to GET method
Something like this
Route::GET('/pay/{orderId}', 'PublicSslCommerzPaymentController#index')->name('payments.pay');

Laravel 5 - How to passing request data from route to controller

I am new in laravel,
How to passed request data into controller ? Just like happen on view ?
Route::get('/kelihatan', function (Request $request) {
return view( 'pages' , [ 'page' => 'index' , '_request' => $request->all() ] );
});
How to passing request data to controller before passed into view or model ? Just like this ??
Route::get( '/{page}', 'UserController#show' );
Mention the path in route first depending upon the type of request i.e. Get or Post
Route::get('/invite/{code}', 'MyController#get_my_action');
Route::post('/invite/{code}', 'MyController#post_my_action');
Then in controller named as MyController create a function like
public function get_my_action($code){
//your code goes here
}
or
public function post_my_action(Request $request, $code)
{
//your code goes here
}
With that route:
Route::get('/{page}', 'UserController#show');
In the controller you can do that:
public function show()
{
$page = request()->route('page');
or that:
public function show($page)
or that:
public function show(Request $request, $page)
Try this:
Routes.php
Route::get( '/{page}', 'UserController#show' );
UserController.php
public function show($page) {
dd($page);
}
Inside your controller define your show function as below:
function show(Request $request)
{
echo $request['page'];//or whatever data you want to pass
}
///add follwoing line before you define controller
use Illuminate\Http\Request;

Handling Custom Exceptions from PHPUnit (Laravel 5.2)

I'm currently playing around with Exception Handler, and creating my own custom exceptions.
I've been using PHPUnit to run tests on my Controller Resource, but when I throw my custom exceptions, Laravel thinks it's coming from a regular HTTP request rathen than AJAX.
Exceptions return different response based on wether it's an AJAX request or not, like the following:
<?php namespace Actuame\Exceptions\Castings;
use Illuminate\Http\Request;
use Exception;
use Actuame\Exceptions\ExceptionTrait;
class Already_Applied extends Exception
{
use ExceptionTrait;
var $redirect = '/castings';
var $message = 'castings.errors.already_applied';
}
And the ExceptionTrait goes as follows:
<?php
namespace Actuame\Exceptions;
trait ExceptionTrait
{
public function response(Request $request)
{
$type = $request->ajax() ? 'ajax' : 'redirect';
return $this->$type($request);
}
private function ajax(Request $request)
{
return response()->json(array('message' => $this->message), 404);
}
private function redirect(Request $request)
{
return redirect($this->redirect)->with('error', $this->message);
}
}
Finally, my test goes like this (excerpt of the test that's failing)
public function testApplyToCasting()
{
$faker = Factory::create();
$user = factory(User::class)->create();
$this->be($user);
$casting = factory(Casting::class)->create();
$this->json('post', '/castings/apply/' . $casting->id, array('message' => $faker->text(200)))
->seeJsonStructure(array('message'));
}
My logic is like this although I don't think the error is coming from here
public function apply(Request $request, User $user)
{
if($this->hasApplicant($user))
throw new Already_Applied;
$this->get()->applicants()->attach($user, array('message' => $request->message));
event(new User_Applied_To_Casting($this->get(), $user));
return $this;
}
When running PHPUnit, the error I get returned is
1) CastingsTest::testApplyToCasting PHPUnit_Framework_Exception:
Argument #2 (No Value) of PHPUnit_Framework_Assert:
:assertArrayHasKey() must be a array or ArrayAccess
/home/vagrant/Code/actuame2/vendor/laravel/framework/src/Illuminate/Foundation/T
esting/Concerns/MakesHttpRequests.php:304
/home/vagrant/Code/actuame2/tests/CastingsTest.php:105
And my laravel.log is over here http://pastebin.com/ZuaRaxkL (Too large to paste)
I have actually discovered that PHPUnit is not actually sending an AJAX response, because my ExceptionTrait actually changes the response on this. When running the test it takes the request as a regular POST request, and runs the redirect() response rather than ajax(), hence it's not returning the correspond.
Thanks a bunch!
I have finally found the solution!
As I said, response wasn't the right one as it was trying to redirect rathen than return a valid JSON response.
And after going through the Request code, I found out that I need to use also wantsJson(), as ajax() may not be the case always, so I have modified my trait to this:
<?php
namespace Actuame\Exceptions;
trait ExceptionTrait
{
public function response(Request $request)
{
// Below here, I added $request->wantsJson()
$type = $request->ajax() || $request->wantsJson() ? 'ajax' : 'redirect';
return $this->$type($request);
}
private function ajax(Request $request)
{
return response()->json(array('message' => $this->message), 404);
}
private function redirect(Request $request)
{
return redirect($this->redirect)->with('error', $this->message);
}
}

Resources