ErrorException: Array to string conversion in file - laravel

I have a problem when updating the URLImg data when I use the PUT method, it throws the following error in Postman 'ErrorException: Array to string conversion in file' but if I use the POST method I have no problem uploading the urls of my images.
public function store(Request $request)
{
$values = $request->except('URLImg');
$data = $request->only('URLImg[]');
if($request->hasFile('URLImg')){
foreach($request->file("URLImg") as $image)
{
$name = Str::random(10).'.'.$image->getClientOriginalExtension();
$path = 'storage/img/';
$image->move($path, $name);
$data[] = $name;
$tramite = Tramite::create($values);
$tramite->URLImg = json_encode($data);
$tramite->save();
}
}else{
$tramite = Tramite::create($values);
$tramite->save();
}
return response()->json($tramite, 201);
public function update(Request $request, Tramite $tramite)
{
$data = $request->only('URLImg[]');
if($request->hasFile('URLImg')){
foreach($request->file("URLImg") as $image)
{
$name = Str::random(10).'.'.$image->getClientOriginalExtension();
$path = 'storage/img/';
$image->move($path, $name);
$data[] = $name;
$tramite->URLImg = json_encode($data);
$tramite->save();
}
}
return response()->json($tramite, 201);
}
Postman Config
Postman Config
Yes, it is almost the same code but I only need to update the URLImg field

Want to use a PUT or PATCH request for form containing file uploads - submit a POST request with method spoofing
<form action="/foo/bar" method="POST">
#method('PUT')
...
</form>
via any javascript framework like vue
let data = new FormData;
data.append("_method", "PUT")
axios.post("some/url", data)
Using _method and setting it to 'PUT' or 'PATCH' will allow to declare route as a PUT route and still use POST request to submit form data
$_FILES will not be populated on a PUT or PATCH request with multipart/form-data - PHP limitation

Related

How to use parameter from function to create an URL? Laravel Routing

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
}

Laravel: Database is not storing my image but showing me only array

I am new to Laravel. I have been trying to save an image to the database. Here is my controller method that I am trying for storing the image
public function store(Request $request){
//validation for form
$validate= $request->validate([
'name' => 'required|min:2|max:140',
'position' => 'required|min:2|max:140',
'salary' => 'required|min:2|max:140',
'joining_date' => ''
]);
//saving form
if($validate){
$employee=new Employee;
$employee->name =$request->input('name');
$employee->company_name =$request->input('company_name');
$employee->position =$request->input('position');
$employee->salary =$request->input('salary');
$employee->joining_date =$request->input('joining_date');
$employee->user_id= auth()->user()->id;
//image saveing method
if($request->hasFile('image')){
$image= $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Employee::make($image)->resize(300, 300)->save( public_path('/employee/images/' . $filename ) );
$employee->image= $filename;
}else{
return $request;
$employee->image= '';
};
$employee->save();
//redirecting to Employee list
return redirect('/employee/details')->with('success','Employee Added');
}
I could save the form while there was no image and redirect it to the details page. but now when I try with the image, instead of saving it and redirecting to the details route, it returns me to the array of row of database like this:
{
"_token": "FPHm9AKuEbRlqQnSgHhjPnCEKidi2xr0usgp7RoW",
"name": "askfjlk",
"company_name": "laksjsflkj",
"position": "lkasjfkl",
"salary": "35454",
"joining_date": "4654-05-06",
"image": "testing.png"
}
What did I do wrong here? please help me out this newb.
You are returning $request object and Laravel does automatic JSON response.
if ($request->hasFile('image')){
// image storing logic which obviously is never started because expression above is false
} else {
return $request; // There is your problem
$employee->image= '';
};
You need to check why you are getting false on $request->hasFile('image').
Also, one tip because you are new to Laravel:
// When you are accessing to $request object you can use dynamic propertes:
$employee->company_name = $request->input('company_name');
// is the same as
$employee->company_name = $request->company_name;
You can check it there: Laravel docs in the section: Retrieving Input Via Dynamic Properties

laravel 5.7 how to pass request of controller to model and save

I am trying to pass $request from a function in controller to a function in model.
THis is my controller function:
PostController.php
public function store(Request $request, post $post)
{
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return redirect(route('post.index'));
}
how save data in model Post.php?
I want the controller to only be in the role of sending information. Information is sent to the model. All calculations and storage are performed in the model
Thanks
You can make it even easier. Laravel has it's own helper "request()", which can be called anywhere in your code.
So, generally, you can do this:
PostController.php
public function store()
{
$post_model = new Post;
// for queries it's better to use transactions to handle errors
\DB::beginTransaction();
try {
$post_model->postStore();
\DB::commit(); // if there was no errors, your query will be executed
} catch (\Exception $e) {
\DB::rollback(); // either it won't execute any statements and rollback your database to previous state
abort(500);
}
// you don't need any if statements anymore. If you're here, it means all data has been saved successfully
return redirect(route('post.index'));
}
Post.php
public function postStore()
{
$request = request(); //save helper result to variable, so it can be reused
$this->title = $request->title;
$this->description = $request->description;
$this->save();
}
I'll show you full best practice example for update and create:
web.php
Route::post('store/post/{post?}', 'PostController#post')->name('post.store');
yourform.blade.php - can be used for update and create
<form action='{{ route('post.store', ['post' => $post->id ?? null]))'>
<!-- some inputs here -->
<!-- some inputs here -->
</form>
PostController.php
public function update(Post $post) {
// $post - if you sent null, in this variable will be 'new Post' result
// either laravel will try to find id you provided in your view, like Post::findOrFail(1). Of course, if it can't, it'll abort(404)
// then you can call your method postStore and it'll update or create for your new post.
// anyway, I'd recommend you to do next
\DB::beginTransaction();
try {
$post->fill(request()->all())->save();
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
abort(500);
}
return redirect(route('post.index'));
}
Based on description, not sure what you want exactly but assuming you want a clean controller and model . Here is one way
Model - Post
class Post {
$fillable = array(
'title', 'description'
);
}
PostController
class PostController extend Controller {
// store function normally don't get Casted Objects as `Post`
function store(\Request $request) {
$parameters = $request->all(); // get all your request data as an array
$post = \Post::create($parameters); // create method expect an array of fields mentioned in $fillable and returns a save dinstance
// OR
$post = new \Post();
$post->fill($parameters);
}
}
I hope it helps
You need to create new model simply by instantiating it:
$post = new Post; //Post is your model
then put content in record
$post->title = $request->title;
$post->description = $request->description;
and finally save it to db later:
$post->save();
To save all data in model using create method.You need to setup Mass Assignments when using create and set columns in fillable property in model.
protected $fillable = [ 'title', 'description' ];
and then call this with input
$post = Post::create([ 'parametername' => 'parametervalue' ]);
and if request has unwanted entries like token then us except on request before passing.
$post = Post::create([ $request->except(['_token']) ]);
Hope this helps.
I find to answer my question :
pass $request to my_method in model Post.php :
PostController.php:
public function store(Request $request)
{
$post_model = new Post;
$saved = $post_model->postStore($request);
//$saved = response of my_method in model
if($saved){
return redirect(route('post.index'));
}
}
and save data in the model :
Post.php
we can return instance or boolean to the controller .
I returned bool (save method response) to controller :
public function postStore($request)
{
$this->title = $request->title;
$this->description = $request->description;
$saved = $this->save();
//save method response bool
return $saved;
}
in this way, all calculations and storage are performed in the model (best way to save data in MVC)
public function store(Request $request)
{
$book = new Song();
$book->title = $request['title'];
$book->artist = $request['artist'];
$book->rating = $request['rating'];
$book->album_id = $request['album_id'];
$result= $book->save();
}

Vuejs Laravel Axios create request

I have a vuejs method which implements axios to send a put/create request over to my laravel api create method passing over some data.
create(data) {
this.mute = true;
window.axios.put('/api/showreels/create', {data}).then(({ data }) => {
this.showreels.push(new Showreel(data));
this.mute = false;
}).catch(error => {
document.write(error.response.data);
});
},
My api.php is setup with the following resource
//Showreel
Route::resource('/showreels' , 'ShowreelController' , [
'except' => ['edit', 'show', 'store']
]);
And I have a create method to handle the request and update persist the data. (Which I have added a load of debugging in)
/**
* Create a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$message = 'sdfsdfsdf';
$message = $message . $request->heading . 'BALLS';
\App::abort(500, $message);
$showreel = new Showreel();
$showreel->heading = $request->heading;
$showreel->subheading = $request->subheading;
$showreel->detail = $request->heading;
$showreel->youtubeid = $request->youtubeid;
$showreel->heading = "test";
$showreel->subheading = "test";
$showreel->detail = "test";
$showreel->youtubeid = "test";
$showreel->save();
return response($showreel->jsonSerialize(), Response::HTTP_CREATED);
}
However laravel is giving me this error.
Not sure why I am getting this error?
Looks like I had the STORE option disabled in my api.php which was closing down the post request option. The post request now takes me through to my store method in laravel.

post method on two actions within same controller in laravel

Following is my route file i.e web.php
Route::post('finddomainname','DomainController#finddomainname')->name('finddomainname');
Route::post('registerdomains','DomainController#registerdomains')->name('registerdomains');
Following is the code on my DomainController for both the actions used,
public function finddomainname(Request $request)
{
$this->validate($request,
['searchdomaintxt'=>'required',
'searchdomainext'=>'required']);
$searchdomaintxt = $request->input('searchdomaintxt');
$searchdomainext = $request->input('searchdomainext');
$domainname="";
if($searchdomaintxt && $searchdomainext)
{
foreach($searchdomainext as $ext)
{
$domainname.=$searchdomaintxt.".".$ext.",";
}
//dd($domainnames);
$domainnames= rtrim($domainname,',');
$response=$this->soap->multidomainsearch($domainnames);
$result=$response['RESPONSE']['DOMAINSEARCH'];
//dd($result);
if($result){
//return redirect()->action('searchresults', array('response' => $result));
return view('domain.searchresults',['response'=>$result]);
}
else
{
return view('domain.searchresults',['response'=>'']);
}
}
}
Following is the second action on which control come after submitting data
public function registerdomains(registerDomainsValidation $request)
{
$domains=$request->input('selecteddomains');
$selectedyear =$request->input('selectedyear');
$domaincontactid=\Session::get('domaincontactid');
$alldomains='';
foreach($domains as $domain)
{
$alldomains.=$domain.",";
}
$alldomains=rtrim($alldomains,',');
$response=$this->soap->registerdomains($alldomains,$domaincontactid,$selectedyear);
return view('domain.searchresults',['response'=>$response]);
}
but when i submit data it will show me this error
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
You are trying to access your POST route using a GET request, that's why you are receiving a MethodNotAllowedHttpException. To solve this issue, make sure that your <form></form> tag contains the appropriate method attribute.
<form action="{{ YOUR_URL }}" method="POST">
...
</form>
Or if you want to perform the request inside your controller, you can use Guzzle to send http requests. In your controller you can do:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST', 'YOUR_URL', [
'form_params' => [
'foo' => 'bar'
]
]);

Resources