Check if laravel model got saved or query got executed - php

I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.
And also can I check if the queries bellow got executed like this
Check if model got saved
Eg:
$myModel = new User();
$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');
$myModel->save();
//Check if user got saved
if ( ! $myModel->save())
{
App::abort(500, 'Error');
}
//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);
Is the above a safe way to check whenever my model got saved or not?
Check if query returned a result
Eg:
$UserProduct = Product::where('seller_id', '=', $userId)->first();
if (! $UserProduct)
{
App::abort(401); //Error
}
Does above return an error if no product where found?
Check if query got executed
Eg:
$newUser = User::create([
'username' => Input::get('username'),
'email' => Input::get('email')
]);
//Check if user was created
if ( ! $newUser)
{
App::abort(500, 'Some Error');
}
//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);
Does above check if a user was created?

Check if model got saved
save() will return a boolean, saved or not saved. So you can either do:
$saved = $myModel->save();
if(!$saved){
App::abort(500, 'Error');
}
Or directly save in the if:
if(!$myModel->save()){
App::abort(500, 'Error');
}
Note that it doesn't make sense to call save() two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...
Check if query returned a result
first() will return null when no record is found so your check works find. However as alternative you could also use firstOrFail() which will automatically throw a ModelNotFoundException when nothing is found:
$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();
(The same is true for find() and findOrFail())
Check if query got executed
Unfortunately with create it's not that easy. Here's the source:
public static function create(array $attributes)
{
$model = new static($attributes);
$model->save();
return $model;
}
As you can see it will create a new instance of the model with the $attributes and then call save(). Now if save() where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$newUser->id){
App::abort(500, 'Some Error');
}

You can also check the public attribute $exists on your model.
if ($myModel->exists) {
// Model exists in the database
}

I would do such move to when I use Model::create method :
$activity = Activity::create($data);
if ($activity->exists) {
// success
} else {
// failure
}
As for the Save method it's easier because $model->save() returns Bool :
$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();
if ($is_saved) {
// success
} else {
// failure
}

/**
* Store a newly created country in storage.
*
* #url /country
* #method POST
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
# Filer & only get specific parameters.
$request = $request->only('code', 'name', 'status');
# Assign login user(Auth Control).
$request['created_by'] = Auth::user()->id;
# Insert data into `countries` table.
$country = Country::create($request);
if(!$country)
throw new Exception('Error in saving data.');
}

Related

Check if a fetched user exists in database. Laravel

I want to check a fetched user exists in DB. Suppose I assigned the authenticated user to a variable and the same user is deleted with another variable. But the first variable holds the value of the deleted user. So I want to check whether user data exists in the DB. Something like this.
$user = Auth::user();
$user1 = Auth::user();
$user1->delete();
if($user->existsInDB()){
//
}
If you have a look at the official documentation you will see that there's a fresh method:
The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:
If we have a look at the source code, the fresh method returns null if the model doesn't exists (for example if you create a new Model) or if it can't be found:
/**
* Reload a fresh model instance from the database.
*
* #param array|string $with
* #return static|null
*/
public function fresh($with = [])
{
if (! $this->exists) {
return;
}
return static::newQueryWithoutScopes()
->with(is_string($with) ? func_get_args() : $with)
->where($this->getKeyName(), $this->getKey())
->first();
}
Now in your code you can just add a null check to achive your goal... something like:
$user = Auth::user();
$user1 = Auth::user();
$user1->delete();
if($user->fresh()){
// !== null => it exists
} else {
// === null => it doesn't exists
}
use can do that with method 'find()' like this :
$user=Users:find(Auth::id())
if($user)
{
//user is exist
}

Call to a member function save() on null

I am using the following code
public function show()
{
$id = Auth::user()->id;
$usuario = User::find($id);
$mascotin = Mascota::all();
$mascota = Mascota::find($id);
$mascota->save();
$cant_mascota = Mascota::count();
$cant_pregunta = Pregunta::count();
return view('usuario.show',[
'usuario' => $usuario,
'mascotin' => $mascotin,
'mascota' => $mascota,
'cant_mascota' => $cant_mascota,
'cant_pregunta' => $cant_pregunta,
]);
}
It gives me this error
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR).Call to a member function save() on null
User Model
public function mascotas(){
return $this->hasMany('App\Mascota','user_id', 'id');
}
Mascota Model
public function usuario()
{
return $this->belongsTo('App\User', 'id','user_id');
}
Route
Route::get('/home', 'UserController#show')->name('home');
Hope you guys can help me, I'm new in laravel and I have like 1 day tring to solve this problem
$usuario = Auth::user();
$id = $usuario->id; // you already have user from Auth or Request, does not need to request database again
$mascotin = Mascota::all();
$mascota = $mascotin->find($id); // you can search in collection
//if you want to create Mascotin if it doesn't exists use Mascota::firstOrCreate(['id' => $id]);
if(!$mascota){
throw new \Exception('Mascota not found', 404); //if $mascota is mandatory
}
$mascota->save(); // this does not have place here unless you are changing $mascota before that
$cant_mascota = $mascotin->count();
$cant_pregunta = Pregunta::count();
Also you should add auth middleware to this route. Only logged users should see it.
I am not sure what "Mascota" means (it will be good to use english when you share your code) but it is not good to have the same id as user. Better use relationships.

Return model with laravel when it was created

I need to send a new model saved as json to front but I can't see column organizationid in response
This is my model
class Organization extends Model
{
protected $table = "core.organizations";
protected $fillable = ['description'];
public $primaryKey = "organizationid";
public $incrementing = false;
public $timestamps = false;
}
and this is my function
public function saveOrganization(Request $request)
{
try {
$description = $request->input('description');
$organization = new Organization();
$organization->description = $description;
$organization->save();
if (!$organization) {
throw new \Exception("No se guardo la organizacion");
}
return response()->json([
'organization' => $organization,
], 200);
} catch (\Exception $ex) {
return response()->json([
'error' => 'Ha ocurrido un error al intentar guardar la organizaciĆ³n',
], 200);
}
}
and this is response
{"organization":{"description":"Restobar"}}
How can I do?
Thanks you!!
Since you've created a new object, and not retrieved one from the database, the only attributes it will know about are the ones that you set.
If you'd like to get the rest of the fields on the table, you will need to re-retrieve the object after you save it.
// create the new record.
// this instance will only know about the fields you set.
$organization = Organization::create([
'description' => $description,
]);
// re-retrieve the instance to get all of the fields in the table.
$organization = $organization->fresh();
$savedOrganization = Organization::create(
[
'description' => $description
]
);
return response()->json([
'organization' => $savedOrganization,
], 200)
And this code is useless
if (!$organization) {
throw new \Exception("No se guardo la organizacion");
}
Something I notice on Laravel 7.x (which might be true for previous versions as well):
I tried handling both creating and updating of new object with save as follows:
public static function saveAnswers(\stdClass $answers) {
if($answers->id) {
$jsonObject = JsonObject::find($answers->id);
} else {
$jsonObject = new JsonObject();
}
$jsonObject->fill((array) $answers);
$jsonObject->user_id = Auth::user()->id;
return $jsonObject->save();
}
This lead to return-value being boolean (true). I was bit baffled, because I had used saving and returning on other endpoints multiple times successfully before. Finally I discovered that returning $jsonObject->save() always returns boolean, but returning just $jsonObject AFTER SAVING returns mutated object! So basically do saving and returning of object on separate commands:
$jsonObject->save();
return $jsonObject;
Don't know what sort of witchery this is, but having worked with C# and JAVA projects I had gotten used to piping methods to first mutate class instance and finally the class instance being returned... Might be that PHP handles this workflow bit differently.

data is not inserted if not exist using save()

I am facing a problem with insert data using save(). using save() i successfully update data.but when the data is not exist in database with perticular id it not insert data.
controller :
public function actionContact()
{
//$profile=new Profile();
$id=YII::$app->user->id;
//$users=User::find()->where('id='.$id)->one();
//$profiles=Profile::find()->where('user_id='.$id)->one();
$this->layout="profile";
$profile=$this->findModel1($id);
$data=Yii::$app->request->post();
if($data && $profile->validate()){
$profile->mobile=Yii::$app->request->post('mobile');
$profile->city=Yii::$app->request->post('city');
$profile->zip=Yii::$app->request->post('zip');
$profile->address=Yii::$app->request->post('zip');
$profile->save();
Yii::$app->session->setFlash("Contact-success", Yii::t("user", "Contact updated"));
return $this->refresh();
}
return $this->redirect(['/users/edit']);
}
Any solution will highly appriciated.
$profile=$this->findModel1($id);
if there is no object found.
if(empty($profile)){
$profile = new Profile();
}
I think you can check this way.
$profile=$this->findModel1($id);
if($profile == null)
{
$profile = new Profile();
}
In this i have checked if model is null then create new model object. and then it performs save.

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
In laravel eloquent, has default exists() method, refer followed example.
if (User::where('id', $user_id )->exists()) {
// your code...
}
One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.
if($user->isEmpty()){
// has no records
}
Eloquent uses collections.
See the following link: https://laravel.com/docs/5.4/eloquent-collections
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
if (User::where('email', 'user#email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first(), not count() if you only need to check for existence.
first() is faster because it checks for a single match whereas count() counts all matches.
It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.
$result = User::find($email)->exists();
If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e
Call to a member function exists() on null.
But the case is different for where() thing.
$result = User::where("email", $email)->exists();
The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
In your Controller
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
In your View - Display Already Exist Message
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
would work with try/catch
->get() would still return an empty array
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Simple, comfortable and understandable with Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
I solved this, using empty() function:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
you have seen plenty of solution, but magical checking syntax can be like,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
can be written as
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user exist!
}else{
// user does not exist
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
If you want to insert a record in the database if a record with the same email not exists then you can do as follows:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.
You can check out the docs here: Laravel upserts doc
You can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But also you can use these ways:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
Note :: Where condition according your requirements.
Simply use this one to get true or false
$user = User::where('email', '=', Input::get('email'))->exists();
if you want $user with result you can use this one,
$user = User::where('email', '=', Input::get('email'))->get();
and check result like this,
if(count($user)>0){}
Other wise you can use like this one,
$user = User::where('email', '=', Input::get('email'));
if($user->exists()){
$user = $user->get();
}
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";

Categories