How to get value an array laravel 4? - php

I just want to ask, how do I get the value of this code with laravel 4?
$auth = DB::select(
'SELECT auth FROM users WHERE username like ?'
, array($username)
);
When I display the result of the code, its echoing "Array" and it always redirecting the user to 'anotherpage' I'm actually doing like:
if (Auth::attempt($userdata))
{
if ($auth==0)
{
return Redirect::to('home');
}
elseif ($auth==1)
{
return Redirect::to('dashboard');
}
else
{
return Redirect::to('anotherpage');
}
}
Please help. Thank you in advance.

First of all, why are you authenticating the user twice through Auth class and manual SELECT query? Auth::attempt is enough. Read it here.
Anyway, assuming you really wanna do it that way, your code isn't working properly because you're assigning $auth to 0 within the if statement; so this :
if($auth = 0)
Is basically this:
if(0) //Which is always false
So, i'd change the if statement to :
if($auth == 0)
Your final code should look like this:
if(Auth::attempt($userdata))
{
$auth = DB::table('users')->where('username', '=', $username)->first()->auth;//Don't use "LIKE" as it may cause huge security issues.
if($auth == 0) {
return Redirect::to('home');
}
else if($auth == 1) {
return Redirect::to('dashboard');
}
else {
return Redirect::to('anotherpage');
}
}

That's what happens when you try to echo an array. Use print_r() instead. It prints a readable output of the contents of an array (or a variable):
$myArray = DB::select('SELECT auth FROM users WHERE username like ?', array($username));
print_r($myArray);
That way, you'll see the contents of the array, and you can then display the specific item.
Enclosing it in <pre> tags will make the output, even more readable:
echo '<pre>';
print_r($myArray);
echo '</pre>';
Or simply:
echo '<pre>', print_r($myArray), '</pre>';

You're using the query builder wrong. Try this:
$auth = DB::table('users')->select('auth')->where('username', 'LIKE', $username)->get();
dd($auth);

Related

Laravel check input in array

How can I check if my form input value exist in controller array?
Code
$admins = User::role(['admin', 'superadmin'])->pluck('id'); // get array of admins id
if($request->input('user_id') == $admins) { // if user_id is include admins id...
// do something
} else {
// do something else
}
Use in_array (docs) to check whether something exists in an array.
if(in_array($request->input('user_id'), $admins)) { // if user_id is include admins id
Try this:
if(in_array($request->input('user_id'), $admins)) { // if user_id is include admins id...
// do something
} else {
// do something else
}
You could as well perform it in a single query:
$user_admin = User::role(['admin', 'superadmin'])->find($request->input('user_id')); // returns null if not found or the $user if found
if($user_admin) { /
// do something
} else {
// do something else
}
If you are working with collections you can use their methods.
In this case you could use contains() method.
$admins = User::role(['admin', 'superadmin'])->pluck('id'); //this return a collection
if($admins->contains($request->input('user_id'))) { // use the contains method of collection
// do something
} else {
// do something else
}

How to pass variables from controller to show their values in blade file

I want to show variables value in blade file. Below is the controller code:-
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with($select_clientlist);
}
else
{
return view('client-database')->withMessage('No Details Found');
}
}
I want to show the values coming in $select_clientlist variable. Below is the code in my blade file:-
#foreach($select_clientlist as $clientlist)
{{$clientlist->firstname}}
#endforeach
And below is the route file code:-
Route::post('client_list_ajax','ClientDatabase\ClientdatabaseController#ClientListReviews');
I am receiving error.
What am I doing wrong?
Pass the variable using compact method
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
view1,view2,view3 are variable names
Since you only pass the variable when there is records wrap your for each inside isset
if (isset($select_clientlist)) {
foreach($select_clientlist as $clientlist) {
}
}
your query should be like this . you may be forget SELECT statement
$select_clientlist = DB::table('users_booking')->select('*')->where('service_provider', '=', 1)->get();
Either use as
return view('client-database')->with('select_clientlist',$select_clientlist);
Or
return view('client-database',compact('select_clientlist'));
Also add in select_clientlist else part to prevent undefined error
public function ClientListReviews()
{
// to show client list get data from users booking table
$select_clientlist =
DB::table('users_booking')>where('service_provider', '=', 1)->get();
if(count($select_clientlist) > 0)
{
return view('client-database')->with('select_clientlist',$select_clientlist);
}
else
{
$select_clientlist = [];
return view('client-database')->with('select_clientlist',$select_clientlist)->withMessage('No Details Found');
}
}
OR check by isset($select_clientlist) in blade file
$__currentLoopData = isset($select_clientlist)?$select_clientlist:[];
Pass that variable to your view either way .. it should be a collection. If there are no records, it is just empty. The foreach wont run if its empty. Its as simple as that. No need to check if anything is set or is empty etc... just always pass that collection.
public function ClientListReviews()
{
$select_clientlist = DB::table('users_booking')->where('service_provider', 1)->get();
$view = view('client-database', compact('select_clientlist'));
if ($select_clientlist->isEmpty()) {
$view->with('message', 'No Details Found');
}
return $view;
}

How to check the given values are updated are not into Database in php

I'm doing webservice using laravel,Here I need to send response after the value get updated into database...
I tried something like this,
public function getPhoneverify(){
$_REQUEST['user_id'] = str_replace('"','', $_REQUEST['user_id']);
$_REQUEST['status'] = str_replace('"','', $_REQUEST['status']);
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->update(array('phone_verified' => $_REQUEST['status']));
if($user)
{
echo "success";exit;
}
else
{
echo "failed";exit;
}
}
But here,always it shows the else part message,even if the value get updated into the database..
How should I do this..
Is there any other option to do this!!..
Someone help me..
If you need to check if the query was successful, I'd suggest a different approach. Assuming the user_id field is unique, following should work:
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->first();
Or you can also retrieve the user like this:
$user = \DB::table('tb_users')->find($_REQUEST['user_id']);
And then update/save it:
$user->fill(array('phone_verified' => $_REQUEST['status']));
$saved = $user->save(); //this will always return true or false.
if($saved)
{
echo "success";exit;
}
else
{
echo "failed";exit;
}
You can use exception handling if you want
try {
$user = \DB::table('tb_users')->where('id', $_REQUEST['user_id'] )->update(array('phone_verified' => $_REQUEST['status']));
}catch(\Exception $e){
//write statements here if query fails
}
By the way as far I know DB::update() returns boolean
The return value will never be true since it returns the number of rows affected by the database transaction.
So you should check for the integer value, not if it is true or false

codeigniter returning false from models

Just wondering if it is necessary to use else {return false;} in my codeigniter model functions or if () {} is enough and it returns false by default in case of failure?
controller:
if ($this->model_a->did()) {
$data["results"] = $this->model_a->did();
echo json_encode($data);
}
model:
public function did()
{
//some code here
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return false;
}
}
in your controller -- test the negative condition first - if nothing came back from the method in your model
if ( ! $data["results"] = $this->model_a->did() ) {
$this->showNoResults() ; }
else { echo json_encode($data); }
so thats saying - if nothing came back - then go to the showNoResults() method.
If results did come back then its assigned to $data
However - in this situation in the model i would also put ELSE return false - some people would say its extra code but for me it makes it clearer what is happening. Versus methods that always return some value.
I think this is more of a PHP question than a CodeIgniter question. You could easily test this by calling your model methods and var_dump-ing the result. If you return nothing from a method in PHP, the return value is NULL.
As much i have experience in CI returning false is not a plus point, because if you return false here then you need to have a condition back in controller which is useless you should be doing like this will save you at least some code of lines
if ($query && $query->num_rows() > 0) {
return $query->result_array();
} else {
return array();
}
so returning an array will save you from many other errors, like type error.

Create like/unlike functionality with Laravel

I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
$like = Like::firstOrNew(array('property_id' => $id));
$user = Auth::id();
try{
$liked = Like::get_like_user($id);
}catch(Exception $ex){
$liked = null;
}
if($liked){
$liked->total_likes -= 1;
$liked->status = false;
$liked->save();
}else{
$like->user_id = $user;
$like->total_likes += 1;
$like->status = true;
$like->save();
}
return Redirect::to('/detalle/propiedad/' . $id);
}
// Model
public static function get_like_user($id)
{
return static::with('property', 'user')->where('property_id', $id)
->where('user_id', Auth::id())->first();
}
// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController#storeLike'));
#Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){
Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();

Categories