laravel route findOrFail() problems - php

new with Laravel and I am trying to add a findOrFail on this specific route and it's giving me a hard time. What am I missing?
Route::get('/listing/{type}/{owner}/{id}/{address}', 'Properties\DisplayController#show');
Whats not working
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return Properties\DisplayController#show::findOrFail($id);
});
Error I am getting
Parse error: syntax error, unexpected '#', expecting ';'
controller/function I'm calling
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id);
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
Thanks for the help!

To return directly on route:
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return App\YourModel::findOrFail($id);
});
https://laravel.com/docs/5.3/eloquent#retrieving-single-models

Since the model is on another server that we connect to using GuzzleHTTP, I could not put findOfFail() on the model.
Here is the edit to the controller. Added in the ['http_errors' => false] which prevents guzzle from returning http errors, and then a if statement using getStatusCode() to find if it was a error 500 or not.
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id, ['http_errors' => false]);
if ($response->getStatusCode() == "500") {
abort(404);
}
else {
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
}

Related

Cloudflare API with PHP problems

I need to sent parameters for the function
Cloudflare\API\Endpoints\AccessRules::createRule()
public function createRule(
string $zoneID,
string $mode,
Configurations $configuration,
string $notes = null
): bool {
$options = [
'mode' => $mode,
'configuration' => $configuration->getArray()
];
if ($notes !== null) {
$options['notes'] = $notes;
}
$query = $this->adapter->post('zones/' . $zoneID . '/firewall/access_rules/rules', $options);
$this->body = json_decode($query->getBody());
if (isset($this->body->result->id)) {
return true;
}
return false;
}
My code:
$key = new Cloudflare\API\Auth\APIKey($userEmail, $api_key);
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$fw = new Cloudflare\API\Endpoints\AccessRules($adapter);
$configData= [
'target' => 'ip',
'value' => '1.2.3.4',
];
$result=$fw->createRule($zoneID,'block',$configData,"Auto block");
And my error:
Uncaught TypeError: Argument 3 passed to Cloudflare\API\Endpoints\AccessRules::createRule() must be an instance of Cloudflare\API\Configurations\Configurations, array given
I do $configData as a object - the same.
Could you tell me - how I should create instance in $configData
You should do this this way:
$configData = new Cloudflare\API\Configurations\AccessRules();
$configData->setIP('1.2.3.4');

403 forbidden when i send PHP code into request to Laravel function

i have a problem in my Laravel function , i am creating a forum for web developers and all requests to the function works fine without no problem in any programming language but when i write PHP code in request which i send to the laravel function it's give me 403 forbidden i don't know why ? this happen when the request include
and if i make
return $req->all(); at the top of the function which receive the request i get Error in the request 301 You can try it by yourself here https://mohamedatef-staging.space/ng-websquare/ in the page of New discussion
https://mohamedatef-staging.space/ng-websquare/new-discuss
public function new_discussion(Request $request){
// return $request->all()['images'];
$data_array = $request->all()['dataArray'];
$data = json_decode($data_array, true);
$validator = Validator::make($data, [
'title' => 'required',
'data' => 'required',
'tags' => 'required',
],[
'title.required' => 'missingTitle',
'data.required' => 'missingData',
'tags.required' => 'missingTags',
]);
if($validator->fails()){
return response($validator->messages(), 200);
}
// $images_array = $request->all()['images'];
// return $images_array;
$urls = [];
if(!empty($request->all()['images'])){
$validator2 = Validator::make($request->all(), [
'images' => 'required|array|min:1',
'images.*' => 'image|mimes:jpeg,jpg,png|max:20000',
], [
'images.*image' => 'image_file_error',
'images.*mimes' => 'image_file_error',
'images.*max' => 'image_file_max',
]);
if($validator2->fails()){
return response($validator2->messages(), 200);
}
$images = $request->all()['images'];
foreach ($images as $image) {
$count = 0 ;
$image_name = time() . '.' . $image->getClientOriginalName();
$image->move(public_path('/images/forum'), $image_name);
$image_url = '/images/forum/'.$image_name;
$urls[] = $image_url;
$count++;
}
}
// }
// return response(['urls' => $urls[0]]);
// return response(['owner' => auth('members')->user()->id]);
$forum_slug = preg_replace('~[^\pL\d]+~u', '-', $data['title']);
$forum_slug2 = strtolower($forum_slug);
$forum = new forum ;
$forum->ownerID = auth('members')->user()->id;
$forum->title = $data['title'];
$forum->slug = $forum_slug2;
$forum->content = $data['data'];
$forum->tags = $data['tags'];
if(!empty($urls[0])){
$forum->img1 = $urls[0];
}
if(!empty($urls[1])){
$forum->img2 = $urls[1];
}
if(!empty($urls[2])){
$forum->img3 = $urls[2];
}
$forum->views = 0;
$forum->status = 0;
$forum->comments = 0;
$done = $forum->save();
if($done){
return response(['status' => 'done']);
}
}

How to get multiple images in laravel api?

I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])

htmlspecialchars() expects parameter 1 to be string, array given - Laravel

These are my controllers
<?php
public static function getAccessToken()
{
$url = 'http://api.tech/oauth/authenticate';
$query = [
'grant_type' => 'client_credentials',
'client_id' => 'E3PuC',
'client_secret' => 'IhvkpkvMdAL7gqpL',
'scope' => 'bookings.read,images.create,images.read,images.update,locations.read,rates.read,rates.update,reports.read,reviews.read,rooms.create,rooms.delete,properties.read',
];
$client = new Client();
$response = $client->get($url, ['query' => $query]);
$content = json_decode($response->getBody()->getContents());
if ($content) {
return $content->access_token;
} else {
return null;
}
}
public function getReviews()
{
$client = new Client();
$access_token = $this->getAccessToken();
$url = 'http://api.tech/hotels/88244/reviews';
$query = [
'access_token' => $access_token,
];
$response = $client->get($url, ['query' => $query]);
$content = json_decode($response->getBody()->getContents());
if ($content->status == 'success') {
// return $content->access_token;
return $content->data;
// return $response;
} else {
return null;
}
}
public function index()
{
$content = $this->getReviews();
return view('channel.channel', [
'content' => $content
]);
}
When i try to output the content in my blade as a link, it says ---
htmlspecialchars() expects parameter 1 to be string, array given
and this is my blade file
This
It also throws an error when i try to output it like thus
{{$content}}
Please How can i solve the error
My question isn't a duplicate cause once i dd it shows an array and i want a link to show the array on a different page
Try Using:
{! $content !}
Or Use:
#json($content)

Symfony PHPUnit Test ( error 500 )

Im testing this function
/**
* #Route("/list", name="_clients")
* #Method("GET")
*/
public function ClientsAction()
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('InvoiceBundle:Clients')->findByUser($this->user());
if($data){
$Clients = array();
foreach($data as $v){
if($v->getCompanyId() != 0 ) {
$companyId = $v->getCompanyId();
} else {
$companyId = '';
}
if ($v->getClient() == 'person'){
$company = $v->getName().' '.$v->getLname();
} else {
$company = $v->getCompany();
}
$Clients[] = array(
'id' => $v->getId(),
'settings' => $company,
'companyId' => $companyId,
'client' => $v->getClient(),
'mobile' => $v->getMobile(),
'email' => $v->getEmail(),
'clientName' => $v->getClientName(),
'delivery' => $v->getDelivery(),
'ContactPerson' => $v->getContactPerson()
);
}
} else {
$Clients = array('data' => 'empty');
}
$response = new JsonResponse($Clients);
return $response;
}
The function it self runs correctly , but then i want to check if my 'Content-Type' is Json with this function
public function testClients()
{
$client = static::createClient();
$client->request('GET', '/clients/list');
$this->assertTrue(
$client->getResponse()->headers->contains(
'Content-Type',
'application/json'
)
);
}
with this i get a FALSE value.
Then i try to do a test for Status code
$this->assertSame(200, $client->getResponse()->getStatusCode());
With this i get error 500 instead of 200 OK
I understand that is why i get a FALSE value in my 'Content-Type' test but i cant get why.
Im doing all this according to the Symfony documentation.
May be i'm doing something wrong or is it just that you cant check the 'Content-Type'?
Any help would be appreciated!
JsonResponse does add the Content-Type header (application/json) so this should not be an issue.
I think the main issue is that you are missing $ on the client->request() line.
Edit :
Before the declaration of your class, did you add #Route("/clients") ?
Or, maybe the data returned by findByUser is not what you expected and calls to $v fail.

Categories