How can I use null or empty in Laravel Controllers? - php

I want to delete a row from likes_table if the table already has a row which contain requested shop_id and user_id combination.
Or, make a new row if it not exists.
However, this following code always executes delete method (returns 204) even if there is no row.
Would you give me any advice?
public function store(Request $request)
{
$liked_id = Like::where('shop_id', $request->shop_id)
->where('user_id', $request->user_id)
->get('id');
$liked = Like::find($liked_id);
if (!empty($liked)) {
Like::where('shop_id', $request->shop_id)
->where('user_id', $request->user_id)->delete();
return 204;
} else {
return Like::create($request->all());
}
}

I solved it myself.
OK:
if ($liked->isEmpty())
NG:
if (!empty($liked))

Related

Why model/variable keeps its value?

I have problem with my code in Laravel Framework. What I am trying to do is sell method inside model. The problem is that $variable keeps its value untill next code execution. How I should make it so it's gonna work like I want to?
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.
Even if you have deleted a record from a database by $this->delete(), $user_item variable still holds a reference to the filled model until the script ends or you destroy the variable.
It seems that you want to return a result of the sell() function. In your case it would be
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->Sell();
I don't know what you are trying to do but below code will solve your issue -
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
$this->ItemData = $this->ItemData->fresh()
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.

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;
}

kohana ---- auto insert

How to insert same data into database after update in ORM?
For example i have function save() and inside this function i have update and it's working, but i don't know how to make insert with old update data. I mean it should make something like history in database. I only hope you can understand what i mean. Thanks for help.
public function save(Validation $validation = NULL)
{
if ($this->loaded()) {
// UPDATE TRIGGER
DB::update($this->_table_name)
->set(array('ud_status' => 'D'))
->where('ud_status', '=', 'A')
->where('ud_uId', '=', $this->ud_uId)
->execute($this->_db);
return false;
} else {
// INSERT TRIGGER
return parent::save($validation);
}
}
$query = DB::insert('users', array('username', 'password'))->values(array('fred', 'p#5sW0Rd'));
https://kohanaframework.org/3.3/guide/database/query/builder#insert

Laravel ORM select query function load() on null

Here's my function to load submissions created by a user.
public function viewSubs()
{
$user = User::find(Input::get('id'));
$submissions = Submission::find($user)->sortByDesc('created_at');
$submissions->load('user')->load('votes')->load('suggestions.votes');
return view('submissions.index' , compact('submissions'));
}
This returns with an error
Call to a member function load() on null
when there are no records on the submission.
How to handle if there are no submission on the DB?
Just check if its null first using an if statement:
public function viewSubs()
{
$user = User::find(Input::get('id'));
if ($submissions = Submission::find($user)->sortByDesc('created_at')) {
$submissions->load('user')->load('votes')->load('suggestions.votes');
}
return view('submissions.index' , compact('submissions'));
}
Also, depending on your DB structure I'm pretty sure you can cut out a lot of the code by utilising your models' relationships by doing something like this:
$user = User::find(Input::get('id'))
->with(['submissions' => function($query) {
$query->orderBy('created_at', 'asc');
}, 'submissions.votes', 'submissions.suggestions.votes']);
Then pass the $user variable to the view, or:
$submissions = Submission::with('user', 'votes', 'suggestions.votes')
->where('user_id', Input::get('id'))
->sortByDesc('created_at')
->first();
Not entirely sure the code will work perfectly, but I'm sure you can tweak it. The point is your code can be a lot shorter and still/or more readable by using relationships you've already set up.

why does deleted record still get returned using eloquent model?

I'm new to laravel, and this is the first framework I'm learning in any language, anyway,
I deleted some records using :
public function getForceLogOut()
{
$input = Input::all();
$e = $input['email'];
echo $e;
DB::select(DB::raw("DELETE FROM active_users WHERE email = '$e'"));
}
But the query executed through the eloquent model returns the object anyway, even though it has been actually been deleted (checked the table in phpMyAdmin)
public static function isLoggedIn()
{
$email = Auth::user()->email;
//$user = ActiveUser::where("email",$email); <== RETURNS THE OBJECT
$user = DB::select(DB::raw("SELECT * fROM active_users where email = '$email'")); // <== WORKS FINE
if ($user) {
return true;
} else {
Auth::logout();
return false;
}
}
Why is this happening? Doesn't eloquent model query the database and works on cached records or something similar?
EDIT: yes, as pointed out, it returns the QueryBuilder object! My mistake.
You are doing this:
$user = ActiveUser::where("email",$email);
which returns you a QueryBuilder, QueryBuilders are used by Laravel to prepare your queries while you're constructing them through your Eloquent model.
If you want to get the result from your database, you should do:
$user = ActiveUser::where("email",$email)->first();
which should return you the query result, or null if the record doesn't exist.

Categories