How to perform a delete operation on a Model? - php

Coming from a Ruby on Rails experience where you load up the rails console to delete a user or all users. I am new to Laravel 5 and I am looking for something similar to delete a user already in the sqlite3 database.
I see where people are talking about User::find(1)->delete(); to delete a user but where to you put that and run in? Is there a console to perform a delete task in? I would like to know how to delete a user without dropping the table. I do not want to soft delete.

You can put this code for example in controller.
You can use
$user = User::find($id);
$user->delete();
if you don't use SoftDeletingTrait trait or
$user = User::find($id);
$user->forceDelete();
if you do, and you want to really remove user from database, not just hide it from results.
More you can read at Laravel page

in Laravel 5 you can use the destroy method.
$user->destroy($id);
and, sure, you have a command line to do so.
$ php artisan tinker
and you can run for example
>> $var = new App\User;
>> $user= $user->find($id);
>> $user->destroy();

Several ways to do this.
If your controller defines the user as an argument:
public function destroy(User $user)
{
return $user->delete();
}
You can also delete any user by $id:
User::destroy ($id);
Assuming you're wrapping these routes with some security.
Edit: Corrected spelling

You can use bellow example to delete data with multiple
parameters......
>
> tableName::where('field_1','=',$para1)
> ->where('field_2,'=',$para2)
> ->delete();

This still works with laravel 7, i use tinker command line and the delete() method:
php artisan tinker
Now i can run commands directly:
> App\User::find($id)->delete();

Related

how to set cron user wise in laravel

I have set cron that runs stock updation for users, Now I have user wise setting if stock updation is set to 'Yes' by user than only that cron should run for particular user.
I have googled it but could not find any solution
Any reference or advice are welcome.
In Laravel it's bad practice to put logic in cron. Use commands and scheduler for that. This problem is common, but another approach that is simple is filter which users need an update in the command.
class UpdateStocks extends Command
{
protected $signature = 'update:stocks';
public function handle()
{
User::where('update_stock', 'Yes')->get()->each(function(User $user) {
// run logic to update the stock
})
}
Put the command in the scheduler.
$schedule->call(new UpdateStocks)->daily();

Laravel Model Restore Event

So I have 2 Models Users & Staff. They have one to one relationship with one another.
User.php 'hasOne' Staff
AND
Staff.php 'belongsTo' User
When I Soft Delete a User I want to soft delete Staff entry as well, I have achieved this using(Works Perfectly):
static::deleting(function ($user) {
$user->staff()->delete();
});
Now I want to restore the staff when I restore the User for that I have tried using this(Not working):
static::restoring(function ($user) {
$user->staff()->restore();
});
But this is not working. The User Entry is deleted but the Staff entry still remains soft deleted.
Can someone help me understand what I am doing wrong here?
Also, Is this the best way to get this done? Or is there some other way this should be done?
PS: I'm using Laravel 5.5
It isn't working because $user->staff() doesn't fetch deleted staff. That's how relationships work by default.
Just replace it with this:
static::restoring(function ($user) {
$user->staff()->withTrashed()->restore();
});
"static::restoring" event is never triggered when restoring a batch of models.
If you're doing something like:
Yourmodel::whereIn('id', [1,2,3])->restore();
It will restore your models but "static::restoring or restored" will never be triggered, instead you could do something like this:
$models = Yourmodel::whereIn('id', [1,2,3])->get();
foreach($models as $model) {
$model->restore();
}

Laravel 5.5 - Only Get Admin Users

I am getting a users details in a Laravel 5.5 controller like this...
$user = Auth::user();
But I want to do a check and see if the user has 'user_type' set to 'admin'
I know I can do a further check once I have the users info but is there a way to combine this into the one statement?
Create a method in User model:
public function isAdmin()
{
return $this->user_type === 'admin';
}
Then use it anywhere in your code:
if (auth()->user()->isAdmin())
Or just do it manually each time:
if (auth()->check() && auth()->user()->user_type === 'admin')
You can even create a global helper and do this:
#if (isAdmin())
This way you can retrieve the user_type of the authenticated user:
$user = Auth::user()->user_type;
As you can see here, the default migration for users does not have a user_type. Hence, if you want to give users certain privileges, you'll have to create it first.
I recommand using a out-of-the-box package. You can (for example) use the package laravel permissions and roles (by Spatie) to do the work for you.

laravel scout: How to update index in controller

Here is my question. I want to update the scout index saved in storage in my controller. Any ideas how to do it?
I am using tntsearch package. I know I can do artisan command in command prompt with $ php artisan scout:import App\\Models\\Paper
But I'm working on a website that everyone can submit their journals in it and I need a powerful search engine on my website. So in this situation, I need to update the index every time a journal submitted. So that everyone can be able to search the journals.
I manage to do a part of this task by making a provider TNTSearchScoutServiceProvider.
here is TNTSearchScoutServiceProvider:
class TNTSearchScoutServiceProvider extends \TeamTNT\Scout\TNTSearchScoutServiceProvider
{
public function boot()
{
$this->app[EngineManager::class]->extend('tntsearch', function ($app) {
$tnt = new TNTSearch();
$driver = config('database.default');
$config = config('scout.tntsearch') + config("database.connections.{$driver}");
$tnt->loadConfig($config);
$tnt->setDatabaseHandle(app('db')->connection()->getPdo());
$this->setFuzziness($tnt);
$this->setAsYouType($tnt);
return new TNTSearchEngine($tnt);
});
// To allow us run commands if we're not running in the console
$this->commands([
ImportCommand::class,
]);
}
}
After adding this provider to config/app.php. In the controller I am using the provider like this:
Artisan::call('tntsearch:import', ['model' => 'App\Models\Paper']);
But this throwes this error:
unlink(C:\wamp64\www\mywbsite\storage/papers.index): Resource temporarily unavailable
Here is what I accomplish so far:
although it throws the error,but I can only get the last updated row in search results and the oldest rows doesn't show up in the search results.
So what are your suggestions? Is it a better way to do this? Or I should check out the site every day and run the artisan commands so that the table can be indexed?
I finally managed to solve this problem:
to update the index in storage you just make a new obj from TNTindexer class; First, you create that index and after that, you select the columns you want to update with query() method. then run() the indexer.Before that make sure to load the configuration. here is the method that I write in the controller:
protected function add_to_search(){
$indexer = new TNTIndexer;
$driver = config('database.default');
$config = config('scout.tntsearch') + config("database.connections.{$driver}");
$indexer->loadConfig($config);
$indexer->createIndex('paper.index');
$indexer->query('SELECT id,title,description,abstract,keywords FROM papers;');
$indexer->run();
}
this way the index always updated through a controller.

Why is laravel migration failing silently?

I am converting a 12 year old frameworkless php app into a Laravel app. The old app had two separate user tables which I have merged. Merging them requires massaging the data. I created a migration to massage the data in one of my tables.
My up() function looks like this:
public function up()
{
$users = User::all();
foreach($users as $user) {
if ($user->staff_id = '0') {
$user->role = '4';
} elseif ($user->role != '1') {
$user->role = '3';
}
$user->save();
}
}
I had run a similar function in a migration moments previously which ran fine. However this one produced the following output:
myusername at local in ~/Sites/tgdp/trunk
> mamp-php artisan migrate
myusername at local in ~/Sites/tgdp/trunk
>
And when I looked in my migrations table and at the User table, it was obvious the migration had not been run.
So, to recap. No error thrown. No "Nothing to Migrate." No success response. No effect on the database. * Edit: No errors listed in the logs.
Any idea why this might have happened?
So, it turns out that the problem was that looping through and saving all of those users was very memory intensive. The solution was to give php limitless access to memory. Like so:
php -d memory_limit=-1 artisan migrate
Once I did that the code ran fine.

Categories