Laravel Eloquent delete() not working - php

Documentation says:
$user = User::find($user_id);
$user->delete();
This doesnt work, however ProductColor::find($color_id) working. $color->delete() Doest return anything, DELETE FROM query doesn't even execute (as seen in debug bar).
But I can delete record with:
ProductColor::destroy($color_id);
Must be something I overlooked earlier, I'm new to Laravel.
I'm using store also, and it working as expected
public function store(Request $request)
{
$color = new ProductColor();
$color->name = $request->color_name;
$color->order = $request->color_order;
$saved = $color->save();
if ($saved) {
return back()->with('message:success', 'Ok');
} else {
return back()->with('message:error', 'Error');
}
}
To sum up
This WORKS
public function destroy($color_id)
{
$deleted = ProductColor::destroy($color_id);
if ($deleted) {
return back()->with('message:success', 'Deleted');
} else {
return back()->with('message:error', 'Error');
}
}
This NOT
public function destroy($color_id)
{
$color = ProductColor::find($color_id);
$color->delete();
}
My Model
<?php
namespace Modules\Shop\Entities;
use Illuminate\Database\Eloquent\Model;
use Modules\Languages\Entities\Language;
class ProductColor extends Model
{
protected $fillable = [];
protected $table = 'product_colors';
}

Sorry, I've figured out the problem. My mistake to post this question.
What I tried to do:
$color = new ProductColor();
$color->find($color_id);
$color->delete();
Should be:
$color = ProductColor::find( $color_id );
$color->delete();
My problem was that I was scared about the IDE complaining about using non-static method 'find'

Please check your model class if you have added soft delete option in that case your record will not be deleted from the database.

Your code is fine - the docs show exactly what you are doing.
If there is no error, and the color is not deleted as expected, then $color_id is not being passed as expected. Try using findOrFail, or add some other check that you found the expected model.

DB::table('pykcodes')
->where('user_id', $user_id)
->delete();
This works directly without using the model.
Just make sure you call use DB; from the top.

My problem was, the name of the property inside the uri on the routes file was incorrect:
Route::delete('/foo/{fo3o}', [DollyController::class, 'delete']);
-----^
I don't know why the controller method was working:
public function delete(Foo $foo)
{
$foo->delete();
return ['message' => 'success'];
}
After correcting it, the problem was solve and the delete method started working again:
Route::delete('/foo/{foo}', [DollyController::class, 'delete']);
------^

You have to add SoftDeletes in User Model:
...
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
protected $dates = ['deleted_at'];
...

Related

Laravel 5.7 - Eager loading with morphMany relationship and custom attribute getter

So I have the following models:
class TemplateEntity extends Model {
protected $table = "TemplateEntities";
const UPDATED_AT = null;
const CREATED_AT = null;
public function element() {
return $this->morphTo("element", "entity_type", "id_Entity");
}
public function getEntityTypeAttribute($entity_type) {
return 'App\\' . $entity_type;
}
}
class Template extends Model {
protected $table = "Template";
const UPDATED_AT = null;
const CREATED_AT = null;
public function entities() {
return $this->hasMany("App\TemplateEntity", "id_Template");
}
}
class TemplateEntity extends Model {
protected $table = "TemplateEntities";
const UPDATED_AT = null;
const CREATED_AT = null;
public function element() {
return $this->morphTo("element", "entity_type", "id_Entity");
}
public function getEntityTypeAttribute($entity_type) {
return 'App\\' . $entity_type;
}
}
I want to eager load template entity elements using Eloquent ORM's ::with() method, however whenever I do this I get an error:
//$template_id is defined as a controller param
$template = Template::with("entities", "entities.element")->where("id", "=", $template_id)->get()
"Class 'App\' not found"
I did some debugging and when I echo $entity_type in TemplateEntity's GetEntityTypeAttribute() method I get an empty value. However, my models generally work fine if I don't use eager loading, but I would like to add it to my application if possible to make it more efficient.
Any help you all can provide would help!
edit: fixed a typo, should have been Template::with instead of $template::with
Part of the problem might be a blank class in that variable. Suggest you use the class name when calling get(). So \App\Template:: instead of $template::.
Another item to help may be the way you are calling the relationship's eager load. Perhaps try to call through the function. This might work better for you:
\App\Template::with(['entities' => function($query){
$query->with('element');
}])->get();
The accessor function might be interfering with the Laravel morph function. I realise you want to use the shortened name of the class in the DB. To do this without the use of the getter (and globally), I suggest using a morphMap.
In AppServiceProvider inside the boot() method:
\Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'MyTemplate' => \App\MyTemplate::class,
'Section' => \App\Section::class,
// etc.
]);
This will allow you to add only 'Section' to the DB and remove the accessor function from your class.

Laravel + Jenssegers\Mongodb: 'WhereHas' and 'Has' returns empty collection

I'm mainly working on two models right now, Form and Notification, and a many-to-many relationship is set up and working for most Eloquent commands, except for whereHas and has. Both just return an empty array, [].
It seems like the developer has had trouble with getting this to work in the past, but seems to have solved it here.
Here's a sample of what I have so far, and what I've tried:
Form.php
class Form extends Eloquent {
protected $connection = 'mongodb';
public function notifications(){
return $this->belongsToMany('App\Api\Forms\Notification', null, 'form_ids', 'notification_ids');
}
}
Notification.php
class Notification extends Eloquent {
protected $connection = 'mongodb';
public function forms()
{
return $this->belongsToMany('App\Api\Forms\Form', null, 'notification_ids', 'form_ids');
}
}
NotificationController.php
<?php
namespace App\Http\Controllers;
use App\Api\Forms\Notification;
use App\Api\Forms\Form;
class NotificationController extends Controller
{
public function getByFormTitle($form_title)
{
// This code retuns the relationship as expected.
// Any forms that are assigned to it are returned.
// $n = Notification::first();
// $n->forms()->get();
// This also returns the relationship correctly, same as before.
// $f = Form::first();
// $f->notifications()->get();
// Nearly identical to the Laravel docs. This returns an empty array, []
$notifications = Notification::whereHas('forms', function ($query) use ($form_title) {
$query->where('form_title', $form_title);
})->get();
return $notifications;
}
}
I get the same result if I use Notification::has('form')->get().
So my question is:
Is it possible to use whereHas and has in Jenssegers\Mongodb Eloquent? Do I have to use different syntax than the official Laravel documentation for it, or do I have to make a raw Mongo query for this?

Having trouble with using ORM inside of route::resource

I'm just following the book of Martin Bean to learn about Laravel 5. He start to teach about laravel with routers and after using some basic Route::get and Route::delete methods he gives a really short example of how to use Route::resource and he says that I let you to do this yourself :)
Structually there is no problem but I'm having trouble when I'm trying to pass ORM inside of the method.
Here is my CatsController.php
namespace firstApp\Http\Controllers;
use Illuminate\Http\Request;
use firstApp\Http\Requests;
use firstApp\Http\Controllers\Controller;
public function show(\firstApp\Cat $cat)
{
return $cat;
//return view('cats.show')->with('cat', $cat);
}
Here is how i use router
Route::resource('cats', 'CatsController');
And this is my Cat.php
-
namespace firstApp;
use Illuminate\Database\Eloquent\Model;
class Cat extends Model {
public $timestamps = false;
protected $fillable = ['name', 'date_of_birth', 'breed_id'];
public function breed(){
return $this->belongsTo('firstApp\Breed');
}
}
When I call http://localhost/firstApp/public/cats/2 an empty object is what I got..
What is the problem?
Thanks.
You're injecting a model into the show method but not doing any queries to get the result.
To fix the problem, change your code to something like this:
public function show(\firstApp\Cat $cat, $id)
{
return $cat->find($id);
}
Note that in the code above I also inject an $id into the show method, so when you hit the http://localhost/firstApp/public/cats/2 URL, 2 will be stored in this variable.
In most cases people from Laravel community do the same thing as follows:
public function show($id)
{
return \firstApp\Cat::find($id);
}
Good luck.

Pulling Data from the Database and passing to View - Laravel Basics

Pretty new to Laravel and looking to get a project off the ground, so I'll cut to the chase. I'm coming over from codeigniter and was hoping for more documentation/examples.
I'm having an issue where my view is coming up blank white. I turned debug to true but I am not seeing any errors being reported.
Controller:
public function clientHome()
{
$data = Contact::orderAsc()->get();
$data->toarray();
return View::make('clientes.clientes', $data);
}
Model:
class Contact extends Eloquent {
protected $table = 'contact';
public function scopeOrderAsc()
{
return $query->orderBy('sort_order', 'asc');
}
}
I have rows in my db table called 'contact'. I have to be missing something small. I went through the code step by step and it is getting caught at the return $query->orderBy('sort_order', 'asc'); line. Thoughts? Also I'm new here so looking forward to contributing in other areas!
You should pass $query into your scope method:
class Contact extends Eloquent {
protected $table = 'contact';
public function scopeOrderAsc($query)
{ // ^^^^^^
$query->orderBy('sort_order', 'asc');
}
}

Laravel update or create an Item

I have this question about Laravel:
I have a my model and my RestfulAPI controller.
Into the store() method I would check if I have an element that already has the field 'myField' (myField id different from 'id') equal to what I have to create. If it already exist then I would like to update, otherwise I would simply create (save())..
Have I to use find() method?
From my experience, you'll have to traverse table and check for uniqueness.
You can create your helper function and use something like array_unique function. Maybe it is worth checking how Validator class is checking that users entry is unique.
Currently we have firstOrCreate or firstOrNew, but I don't think they really fit your needs. For instance, firstOrCreate will try to locate a row by all attributes, not just some, so an update in this case wouldn't make sense. So I think you really would have to find it, but you can create a BaseModel and create a createOrUpdate method that could look like this:
This is untested code
class BaseModel extends Eloquent {
public function createOrUpdate($attributes, $keysToCheck = null)
{
// If no attributes are passed, find using all
$keysToCheck = $keysToCheck ?: $attributes;
if ($model = static::firstByAttributes(array_only($keysToCheck, $attributes))
{
$model->attributes = $attributes;
$model->save();
}
else
{
$model = static::create($attributes);
}
return $model;
}
}
This is an implementation of it:
class Post extends BaseModel {
public function store()
{
$model = $this->createOrUpdate(Input::all(), ['full_name']);
return View::make('post.created', ['model' => $model]);
}
}

Categories