I'm trying to have some after middleware so that if the request was ajax, only render part of the view. I'm having issues though.
My method in my controller:
$data = $this->repository->getUser($id);
$view = View::make('site.user')->withData($data);
return $view;
My middleware:
$response = $next($request);
if(Request::ajax()){
$response->renderSections()['content'];
}
return $response;
I get the error:
Call to undefined method Illuminate\Http\Response::renderSections()
To get the response you need to use a after Middleware which is you are doing now so, you have response as given below:
$response = $next($request);
Now you may try this:
$content = $response->getOriginalContent()->renderSections()['content']
Related
How do I inspect the JSON response in the terminal exactly how it would be returned from the ConversationResource?
Controller
public function show(Conversation $conversation)
{
$conversation->load('participants');
$messages = $conversation
->messages()
->with('sender')
->latest()
->paginate(10);
return new ConversationResource($conversation);
}
Test
/** #test */
public function a_user_can_create_conversation_if_one_doesnt_exist()
{
$this->withoutExceptionHandling();
$this->actingAs($user = User::factory()->create());
$friend = User::factory()->create();
$response = $this->json('GET', '/api/conversation/'. $friend->id)
->assertStatus(201);
dd($response->original);
}
You assign $response to result of assertStatus(). I have no idea what assertStatus returns but likely it does not have json content. I would try to assing to a variable result of this
$response = $this->json('GET', '/api/conversation/'. $friend->id);
and then
dd($response);
Also it would be good to setup xdebug and step trough code, but it is not that easy especially for tests.
If that does not work, then just call same url with https://www.php.net/manual/en/function.file-get-contents.php
and assing to variable and see what it has.
I'm sending an URL hashed and when i get it i have to show a view on Laravel, so i have those functions on the controller and also some routes:
This are my routes:
Route::post('/sendLink', 'Payment\PaymentController#getPaymentLink');
Route::get('/payment?hash={link}', 'Payment\PaymentController#show');
And this are the functions i have on my controller:
public function getPaymentLink (Request $request){
$budgetId = $request['url.com/payment/payment?hash'];
$link = Crypt::decryptString($budgetId);
Log::debug($link);
//here to the show view i wanna send the link with the id hashed, thats why i dont call show($link)
$view = $this->show($budgetId);
}
public function show($link) {
$config = [
'base_uri' => config('payment.base_uri'), ];
$client = new Client($config);
$banking_entity = $client->get('url')->getBody()->getContents();
$array = json_decode($banking_entity, true);
return view('payment.payment-data')->with('banking_entity', $array);
}
And this is getting a "Page not found" message error.
What i want to to is that when i the client clicks on the link i send him that has this format "url.com/payment/payment?hash=fjadshkfjahsdkfhasdkjha", trigger the getPaymentLink function so i can get de decrypt from that hash and also show him the view .
there is no need to ?hash={link} in get route
it's query params and it will received with $request
like:
$request->hash
// or
$request->get('hash')
You need to define route like this:
Route::get('/payment/{hash}', 'Payment\PaymentController#show');
You can now simply use it in your Controller method like below:
<?php
public function getPaymentLink (Request $request,$hash){
$budgetId = $hash;
// further code goes here
}
I want to test back() function in laravel but I am not sure how to do that .
For e.g
public function destroy($id)
{
$query = Query::findorfail($id);
$query->delete();
return back()->with('success','Query deleted successfully');
}
In the above method the url is redirected back . But Can I create a test so that I can assert back()
I have checked the TestResponse class. A function like assertRedirectBack is not yet provided.
I think assertRedirect is gonna work:
$response = $this->delete(...);
$response->assertRedirect($uri);
The previous url could be stored in session. I am not sure about that. So please try this:
$response->assertRedirect(session()->previousUrl());
Try with return redirect()->back();
Use TestCase's from (from MakesHttpRequests trait)
$response = $this
->from('{route}') // without this would redirect to '/'
->delete('/asset/{id}');
$response->assertRedirect('{route}');
I'm trying to call my own laravel api with POST method but I am not getting the post values in get_cities_list method.
LocationController.php
public function get_cities(){
$params = array('country_id' => 1);
$req = Request::create('api/get_cities_list', 'POST', $params);
$response = json_decode(Route::dispatch($req)->getCOntent());
print_r($response);
}
Api/CommonController.php
public function get_cities_list(Request $request){
print_r($request->all()) //empty array
print_r($_POST) //empty array
}
Use guzzle for sending request with php.
You could also use vue to set it up. Or ajax calls.
Could you provide your web.php?
I have RESTful service that is available by endpoints.
For example, I request api/main and get JSON data from server.
For response I use:
return response()->json(["categories" => $categories]);
How to control format of response passing parameter in URL?
As sample I need this: api/main?format=json|html that it will work for each response in controllers.
One option would be to use Middleware for this. The below example assumes that you'll always be returning view('...', [/* some data */]) i.e. a view with data.
When the "format" should be json, the below will return the data array passed to the view instead of the compiled view itself. You would then just apply this middleware to the routes that can have json and html returned.
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->input('format') === 'json') {
$response->setContent(
$response->getOriginalContent()->getData()
);
}
return $response;
}
You can use for this Response macros. For example in AppServiceProvider inside boot method you can add:
\Response::macro('custom', function($view, $data) {
if (\Request::input('format') == 'json') {
return response()->json($data);
}
return view($view, $data);
});
and in your controller you can use now:
$data = [
'key' => 'value',
];
return response()->custom('your.view', $data);
If you run now for example GET /categories you will get normal HTML page, but if you run GET /categories?format=json you will get Json response. However depending on your needs you might need to customize it much more to handle for example also redirects.
With your format query parameter example the controller code would look something like this:
public function main(Request $request)
{
$data = [
'categories' => /* ... */
];
if ($request->input('format') === 'json') {
return response()->json(data);
}
return view('main', $data);
}
Alternatively you could simply check if the incoming request is an AJAX call via $request->input('format') === 'json' with $request->ajax()