how to search a value from table in Laravel - php

I am trying to search a value from database table and display result to web site using laravel. my controller.php code is here
else
{
try
{
$pname = Input::get('pname');
$parents = ForumParent::where('pname', $pname)->first();
if(empty($parents))
{
throw new \Exception("Parent not found");}
return Redirect::route('view',$parents->paddress);
}
catch (Exception $e)
{ return "not value";
//abort(404);
}
}
}
public function view($paddress)
{
$parents=ForumParent::find($paddress);
$users=User::all();
return View::make('search.viewsearch')
->with('parents',$parents)
->with('users',$users);
}

Change this:
$parents = ForumParent::where('pname', $pname)->first();
to this:
$parents = ForumParent::where('pname', '=', $pname)->first();
OR
$parents = ForumParent::where('pname','LIKE', '%' . $pname . '%')->first();
See, if that helps.

Related

Convert procedural code into class for Blobs

So I have the following code that I built out that grabs some images from an Azure storage library:
$accountName = 'teststorageaccount';
$accountKey = '**';
$containerName = 'users';
$connectionString = "DefaultEndpointsProtocol=http;AccountName={$accountName};AccountKey={$accountKey}";
$blobClient = ServicesBuilder::getInstance()->createBlobService($connectionString);
try {
$blob_list = $blobClient->listBlobs($containerName);
$blobs = $blob_list->getBlobs();
// Grab all the blob links
foreach ($blobs as $blob) {
echo $blob->getUrl() . "</br>";
}
} catch(ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
Then I'm getting the following results back:
http://teststorageaccount.blob.core.windows.net/users/ABREUG.jpg
http://teststorageaccount.blob.core.windows.net/users/ABUKHADA.jpg
http://teststorageaccount.blob.core.windows.net/users/ACHANT.jpg
http://teststorageaccount.blob.core.windows.net/users/ACQUISTE.jpg
Now this is where I would need some help .. I'm practicing on building out everything in a class, and this is how far I've come:
class AzureStorage
{
private $accountName;
private $accountKey;
private $containerName;
public static function init()
{
return new AzureStorage([
'accountName' => 'teststorageaccount',
'accountKey' => '***',
'containerName' => 'users',
]);
}
/**************************************************************************/
public function __construct(array $data = [])
{
if (count($data) === 0) {
return;
}
$this->load($data);
}
public function load(array $data) : void
{
if (isset($data['accountName'])) {
$this->accountName = $data['accountName'];
}
if (isset($data['accountKey'])) {
$this->accountKey = $data['accountKey'];
}
if (isset($data['containerName'])) {
$this->containerName = $data['containerName'];
}
}
public function connect()
{
$connectionString = "DefaultEndpointsProtocol=https;AccountName={$this->accountName};AccountKey={$this->accountKey}";
$blobClient = ServicesBuilder::getInstance()->createBlobService($connectionString);
return $blobClient;
}
public function getContainers() : array
{
$containers = $this->connect()->listContainers();
return $containers->getContainers();
}
public function getBlobURLs()
{
try {
$blob_list = $this->connect()->listBlobs($this->containerName);
$blobs = $blob_list->getBlobs();
// Grab all the blob links
foreach ($blobs as $blob) {
echo $blob->getUrl() . "</br>";
}
} catch (ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
echo $code.": ".$error_message."<br />";
}
}
}
The problem: How would I be able to use the try and catch inside the getBlobURLs method and then output the results? I'm unable to get results when calling it outside the class.
Here is what I'm doing:
$test2 = new \AzureStorage\AzureStorage([
'accountName' => 'teststorageaccount',
'accountKey' => '***',
'containerName' => 'users',
]);
Now if I call the following (I get an array of containers, which works perfectly):
$containers = $test2->getContainers();
//var_dump($containers);
But if I do the following (I get no results outputted back):
$blobs = $test2->getBlobURLs();
var_dump($blobs);
Does anyone know why I might not be getting the URLs back?
You do have a return statement in getContainers function but not in getBlobURLs.
public function getBlobURLs(){
try {
$blob_list = $this->connect()->listBlobs($this->containerName);
$blobs = $blob_list->getBlobs();
$blobUrls = [];
// Grab all the blob links
foreach ($blobs as $blob) {
$blobUrls[] = $blob->getUrl();
}
return $blobUrls;
} catch (ServiceException $e) {
return false;
}
}
Now if you want to display blob url list then
$blobs = $test2->getBlobURLs();
if($blobs === false){
echo 'Error while getting blob urls.';
}
else{
foreach($blobs as $blobUrl){
echo $blobUrl . "</br>";
}
}

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

Array to string conversion Error in Laravel 4.2

I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.

Kohana 3.2 - Database search returns empty object

Try to make 'archive' for my blog. If the search run for unavaliable items the return is an empty object. Here is my code:
For example wrong input:
http://www.my-site.com/archive/2011/01/27 - in database no post with this date 2011-01-27
The controller action:
public function action_archive() {
$posts_model = new Model_Posts();
// Év pl.: 2012
if($year = $this->request->param("year")) {
// Hónap pl.: 2012-03
if($month = $this->request->param("month")) {
// Nap pl.: 2012-03-27
if($day = $this->request->param("day")) {
if ($posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
} else {
if($posts = $posts_model->get_post_by_date($year . "-" . $month)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
}
} else {
if($posts = $posts_model->get_post_by_date($year)) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
}
} else
// Nem található archívum
throw new HTTP_Exception_404;
return false;
}
I am try to throw 404 exception if the search fails. Here comes the model:
public function get_post_by_date($date) {
try {
return DB::select()
->from("posts")
->where("date", "like", "$date%")
->and_where("publish", "=", "1")
->as_object()
->execute();
} catch (Database_Exception $e) {
Kohana::$log->add(Log::ERROR, Database_Exception::text($e));
}
return false;
}
If you need just to check if there is a particular entry in the database use
->execute()->count();
In your case you will need the actual posts, so you can use the count method of the Database_Result class (it implements the Countable interface).
$posts = $posts_model->get_post_by_date($year . "-" . $month . "-" . $day);
if ($posts->count()) {
$this->template->content = View::factory('posts/default')
->bind('posts', $posts);
} else
throw new HTTP_Exception_404;
And remove that try-catch block. You don't need it if your query is correct.

Rewrite this code in a neater fashion, without so many else's

I want to rewrite this code without so many "else's", but still keep it efficient in terms of not checking things or running queries if not needed.
Can someone suggest a better way to write this function?
public static function fetch($content) {
products_library::init();
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
//check the cache
if (file_exists($cache)) {
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if ($mod_date) {
$mod_date = strtotime('date_modified');
if ($cache_date >= $mod_date) { //serve the cache
try {
$soldout = filewriter::read($cache);
$soldout = unserialize($soldout);
} catch (Exception $e) {
$soldout = self::query();
}
}
else
$soldout = self::query();
}
else
$soldout = self::query();
}
else
$soldout = self::query();
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
Thanks
Refactored it into a method that returns instead of else statements
private static function getSoldout() {
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
//check the cache
if (!file_exists($cache)) {
return self::query();
}
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if (!$mod_date) {
return self::query();
}
$mod_date = strtotime('date_modified');
if ($cache_date < $mod_date) {
return self::query();
}
try {
//serve the cache
$soldout = filewriter::read($cache);
$soldout = unserialize($soldout);
return $soldout;
} catch (Exception $e) {
return self::query();
}
}
public static function fetch($content) {
products_library::init();
$soldout = self::getSoldout();
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
I don't understand this line, is there a bug there?
$mod_date = strtotime('date_modified');
Set $soldout to NULL. Then remove the else $soldout = self::query() statement.
After the if statement test $soldout for NULL and it true run the query.
A switch-case block would work wonders here. You'd just have a break statement that would point to a default case. However, if I were in your shoes, I'd attempt to refactor the whole thing, which would take more than a quick fix.
Something like this might work. I'm not sure what's happening inside all the ifs and why you need so many, it might be more compact.
public static function fetch($content) {
products_library::init();
self::$cache = $cache = url::assetsPath() . '../cache/soldout_cache';
$soldout = self::fetchCache($cache);
if ($soldout === false)
{
$soldout = self::query();
}
$data['items'] = $soldout; // print_r($items); exit;
$html = view::load('Product_Display', $data, true);
return $html;
}
public static function fetchCache($cache) {
if (file_exists($cache)) {
$cache_date = filectime($cache);
db::select('date_modified');
db::orderBy('date_modified DESC');
db::limit(1);
$mod_date = db::get('sc_module_products')->fetch(PDO::FETCH_ASSOC);
if ($mod_date) {
$mod_date = strtotime('date_modified');
if ($cache_date >= $mod_date) { //serve the cache
try {
$result = filewriter::read($cache);
$result = unserialize($soldout);
return $result;
} catch (Exception $e) {
return false;
}
}
}
}
return false;
}
Seems to me as if you could default $soldout to be self::query() by setting it to that before the first if check then remove all the elses, so if the conditions doesn't match it will still be self::query(). Might not work depending on what self::query() does.

Categories