Which HTTP request should I use while using updateOrCreate() method in Laravel? - laravel

I'm using updateOrCreate but should I use Post Http Request or Put request while I'm using it?

We doesn't know your architecture so it's difficult to give you an appropriate answer.
But, speaking in general termes, A CRUD use the methods as follow:
GET index()
GET create()
POST store()
GET edit($id)
PATCH update($id)
DELETE destroy($id)
In your scenario, I assume you doesn't know the ID of your resource.
In that case it can't be a PATCH (or PUT). The left over would be POST.

Related

How does a Laravel controller method handle multiple Form Request parameters?

I am getting back to Laravel after several years and trying to understand how an already existing REST API coded in Laravel works. I can't understand how a particular controller method with multiple Form Request parameters works (or if it actually does).
The REST API was coded in Laravel 5.1. I've looked at the official documentation (both 5.1 and the latest) and tried to search the web and SO for related topics (e.g., "laravel controller multiple form requests", "laravel controller multiple type-hint requests", etc.), but I can't seem to find a clear explanation. Maybe I'm looking at it from a wrong angle.
public function store(ProductRequest $productRequest, PromoRequest $promoRequest)
{
// Validate product
$product = new Product($productRequest->all());
// Validate promo
if ($promoRequest->get('promo')) {
$promo = new Promo($promoRequest->get('promo'));
}
...
}
In most documentation, the controller would accept only one Request object. I did actually see some examples that have multiple Form Request parameters, but often they were recommended to use only one Form Request. But best practice aside, how does this code work? When this method is called, how does Laravel know how to split the Request into two separate Form Request classes?
Please feel free to let me know if and how I can explain my question more clearly.
you can write like this:
function example(Request $request) {
$productRequest = new ProductRequest($request->all());
$promoRequest = new PromoRequest($request->all());
}
but on validate you should change the way to this:
$data = $productRequest->validate($productRequest->rules());
another way that i test in laravel 8 is to add both form request object in methd parameters like :
function example(ProductRequest $productRequest,PromoRequest $promoRequest) {
$productRequest->validated();
$promoRequest->validated();
}
The Laravel service container is a powerful tool for managing class
dependencies and performing dependency injection. Dependency injection
is a fancy phrase that essentially means this: class dependencies are
"injected" into the class via the constructor or, in some cases,
"setter" methods.
You can read more about it here: https://laravel.com/docs/5.8/container
Edit: Additional question: Still, I can't understand how the HTTP request (which is only one) can be split into two different Request classes?
The HTTP request isn't split; it is merely sent through both classes.
Ex:
function example(Request $request) {
$productRequest = new ProductRequest($request);
$promoRequest = new PromoRequest($request);
}
Would be the same.

\Request::getSession() returns NULL in Controller construct

I want to get the session id of the user each time a page is loaded so I use \Request::getSession()->getId() in the controller construct but I get this error
Call to a member function getId() on null
If I use same code in any of the route methods, it works.
How can I solve this?
Try use Illuminate\Support\Facades\Auth; Auth::getSession()->getId();
This is the default functionality of Laravel. Session data is no longer available in the constructor. See:
laravel - Can't get session in controller constructor
Taylor's word about it :
It’s very bad to use session or auth in your constructor as no request has happened yet and session and auth are INHERENTLY tied to an HTTP request. You should receive this request in an actual controller method which you can call multiple times with multiple different requests. By forcing your controller to resolve session or auth information in the constructor you are now forcing your entire controller to ignore the actual incoming request which can cause significant problems when testing, etc.
This worked for me:
public function __construct()
{
// No session access from constructor work around
$this->middleware(function ($request, $next) {
\Request::getSession()->getId();
return $next($request);
});
}

I can not get inputs file from a put or patch request in Laravel

Description:
I can not check exist file if using put/patch method.
Image description
The picture put method when using post man
Expected:
I can check exist file if using put/patch method similar using post method.
Image description
The picture post method when using post man
My code example:
public function update(Request $request, $id){
dd($request->hasFile('logo'));
}
check your form's attribute . it must have enctype="multipart/form-data"
I can't see all of your data but make sure you are including CRSF token.
https://laravel.com/docs/5.7/csrf
Hope this helps.

Laravel $request->all() correctly returns data, but $_POST completely empty

I am making an ajax post request to the server, posting json data. In firebug I can see the network post call going through along with the json data.
In Laravel I was trying to do a simple var dump of the $_POST data and have just wasted a fair bit of time being confused as to why this should be completely empty. However, when I use the Request facade, my data is there.
ie. this just gives me an empty array:
public function test(){
Log::info($_POST);
}
...yet this prints my data, as I expect:
public function test(Request $request){
Log::info($request->all());
}
Why?
Edit
Thanks, #Webdesigner. The http verb is definitely post, as my method is called in my routes file via
Route::post('/image-upload', 'EntryController#test'); // Note "post" verb
I don't think $request->post() is valid in Laravel 5.4 as this throws an BadMethodCallException: Method post does not exist. error. However, I can confirm that
Log::info($request->method()); // POST
also tells me the method is post.
Very strange. I guess you're right that some part of the app is overwriting the $_POST global, though I have no idea why/where/how. Probably not relevant, but this call is being made from Angular 4.
Thanks for your help anyway!
This is not the normal behavior of Laravel. I tested this on a fresh Laravel 5.5 site and just did a Form submit and an Ajax POST request to the same Route.
Both give me the same result. A POST Request should have at least the CSRF Token as _token with a value.
One other point is $request->all() is not only the the content of $_POST so to have a fair compression you should try $request->post().
BTW only because you did a POST request do not mean that the data is send by the POST Method, it could be that the data you see in $request->all() is from $_GET and $_COOKIE, etc and only the Method was a POST.
Last but not least there it the option that some part of your APP is deleting the content of the Superglobal Variables. $_POST and the others are not like constants, so they can be changed during runtime e.g. $_POST = [];
I don't thing that there is a difference in Laravel 5.4.27.

Laravel 5 - Middleware get user ID and send to controllers

Hello guys !
I'm working on an API that has a middleware authenticating the user with a unique ID. After making sure that this user exists, I want to send his database ID to the controller coming next, whichever it is.
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
How do I do that ?
Thanks !
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
It depends on what you want to do and how you routes are declared.
The routing is one of the first thing initialized by Laravel. You cannot pass parameter at run time (correct me if I'm wrong).
Plus, the controllers called after all midlewares has done their work.
I cannot garanty it's the more "beautiful" way to do this, but what i'm use to do is using Session::flash() or Session::put() when I want to pass parameters to my controllers at run time.
I use Session::flash() if the parameter has a one request life time, and Session::put() when I want the variable be more 'consistent' across the whole application.
I don't know if I am clear or not, tell me :)
Well, as long as you don't send that ID passing through the HTTP protocol, you should be fine since the user won't be able to tamper with the data.
That said, if you are using Laravel's built-in Auth module, you should just do an Auth::user() call at the other controller and it will give you the authenticated user.
If that isn't an option, you should create a function in the other controller that accepts $id as a parameter. You can call that function from within the first controlling by constructing the second controller throug $secondController = App->make(SecondController) and then $secondController->receiverFunction($id)
If you want the currently-authenticated user available in your application, just add it your base controller:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
abstract class Controller {
protected $auth;
protected $currentUser;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->currentUser = $this->auth->user();
}
}

Resources