Hello i am trying to make a simple delete function but its showing an error
This is the code from the controller:
public function destroy($id)
{
$clientOrder = ClientHasOrder::where('order_id',$id)->firstOrFail();
$clientOrder->delete();
return redirect('/')->with('msg','Order Deleted successfully!');
}
This is the model code:
class clientHasOrder extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'order_id',
'product_id',
'amount',
];
}
This is the migration file:
public function up()
{
Schema::create('client_has_orders', function (Blueprint $table)
{
$table->string('order_id')->constrained();
$table->foreignId('product_id')->constrained();
$table->string('amount')->default('200');
});
}
And when i click delete button this is the error im getting:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
delete from
`client_has_orders`
where
`id` is null
showing this line in red: $clientOrder->delete();
When i change the name of column from order_id to id the code works but i dont want to call it id
try it without firstorfail() because you table dose not have an ID.
public function destroy($id)
{
$clientOrder = ClientHasOrder::where('order_id', $id)->delete();
return redirect('/')->with('msg', 'Order Deleted successfully!');
}
Related
I've created an observer to complete the user_id when a user adds a new department.
The created method in the DepartmentObserver:
public function created(Department $department)
{
//
if (auth()->check())
{
$department->created_by_user_id = auth()->id();
$department->save();
}
}
The model:
protected $fillable = [
'deptname',
'created_at',
'updated_at',
'deleted_at',
'created_by_user_id'
];
public function user()
{
return $this->belongsTo(User::class,'created_by_user_id');
}
Then registered the obeserver in the AppServiceProvider Class
public function boot()
{
//
Department::observe(DepartmentObserver::class);
}
I get the following error:
SQLSTATE[HY000]: General error: 1364 Field 'created_by_user_id' doesn't have a default value (SQL: insert into departments (deptname, updated_at, created_at)
I think the oberserver is not firing on the create event. I also tried composer dump and php artisan config:cache
and it didn't work. I'm on laravel 8 (Breeze, not Jetstream)
I have been trying to solve a problem for couple hours.
Basically I'm getting:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tp-laravel.image_location' doesn't exist (SQL: select location_id from image_location where image_id = 3) error.
Is this coming from a bad controller/model/migration? This is happening when I try to add an image in my website.
I have been trying to change stuff, add stuff and look on google a lot, but nothing solved it.
Image.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Image extends Model
{
protected $fillable = ['name'];
public function locations()
{
return $this->belongsToMany(Location::class);
}
public function getUpdatedAtAttribute($date)
{
return Carbon::parse($date)->locale('fr')->diffForHumans(Carbon::now());
}
}
Location.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Location extends Model
{
protected $fillable = ['name'];
public function locations()
{
return $this->belongsToMany(Image::class);
}
}
Here are the create and store methods from my controller:
public function create()
{
$locations = Location::pluck('name', 'id');
$users = User::pluck('name', 'id');
return view('posts.create', compact('locations'));
}
public function store(Request $request)
{
$image = Image::create(request()->all());
$image->locations()->sync(request()->get('locations'));
$user->users()->sync(request()->get('users'));
return redirect('/accueil');
}
And finally my image migration
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->BigInteger('location_id')->unsigned()->index();
$table->BigInteger('user_id')->unsigned()->index();
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name', 100);
$table->timestamps();
});
When I press the create button in my view, the submit it's supposed to add the image in the database with user and location linked to it as a foreign key but the above error pops up.
Thanks!
The error is coming from
public function locations()
{
return $this->belongsToMany(Location::class);
}
Laravel assumes that you have intermediate table named alphabetically, for that is image_location and this table does not exist on your database.
The only way is to create such table, or if you have created the table with different name you can pass second parameter as table name. So it became:
public function locations()
{
return $this->belongsToMany(Location::class, 'TABLE_NAME');
}
I am extremely new to Laravel. You could help me with a small problem:
I can not return in a collection, only the value of a specific column in a relation defined in the model. I will explain:
I have 2 tables:
1 - Tomos
2 - Documents
Migrations:
1- Tomos
private $table = 'tomos';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable(false);
$table->text('description')->nullable(true);
$table->boolean('active')->default(true);
$table->timestamps();
});
}
2- Documents
private $table = 'documents';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create($this->table, function (Blueprint $table) {
$table->increments('id');
$table->date('date')->nullable(false);
$table->integer('provider_id');
$table->integer('tomo_id');
$table->string('folio')->nullable(false);
$table->integer('user_id');
$table->text('description');
$table->timestamps();
$table->foreign('provider_id')
->references('id')->on('providers');
$table->foreign('tomo_id')
->references('id')->on('tomos');
$table->foreign('user_id')
->references('id')->on('users');
});
}
Relations
1- Tomo
public function document()
{
return $this->hasMany(Document::class);
}
2- Document
public function tomo()
{
return $this->belongsTo(Tomo::class);
}
Controller
class Documents extends Controller
{
public function read(Request $request)
{
$provider = $request->only('id');
$documents = Document::select(['id', 'date', 'tomo_id', 'description'])
->with([
'tomo' => function ($query) {
$query->select('id', 'name');
}
])->orderBy('date', 'ASC')
->paginate(25);
return $documents;
}
}
I'm getting the following response in JSON:
current_page 1
data […]
0 {…}
id 2
date 2018-12-01
tomo_id 1
description 1
tomo {…}
id 1
name Tomo 1
But ... I do not want the key ('tomo') to return an object, I want it to return the value of the column ('name') as a string. Example:
current_page 1
data […]
0 {…}
id 2
date 2018-12-01
tomo_id 1
description 1
tomo Tomo 1
Thank you very much in advance..
First you need to add protected $appends = array('tomo_name'); as attribute, because this is one that doesn't exist on the model table.
public function getTomoNameAttribute()
{
return $this->tomo()->name;
}
After this, you can access the tomo name like this ->tomo_name
I'm not 100% sure that this code will work with just copy paste, but you might get the idea and work on it a little bit more.
Oh and be aware that loading the attribute, will query the database for that "tomo" every time.
Thank you very much to: Peter and Munteanu Petrisor
In special to : Munteanu Petrisor
I have been able to solve my problem with the solution that you propose to me, previously I had achieved it using 'join':
class Documents extends Controller
{
public function read(Request $request)
{
$provider = $request->only('id');
$documents = Document::join('tomos', 'documents.tomo_id', '=', 'tomos.id')
->join('users', 'documents.user_id', '=', 'users.id')
->where(['provider_id' => $provider])
->paginate(25, array(
'documents.id',
'documents.date',
'documents.folio',
'documents.description',
'tomos.name as tomo',
));
return $documents;
}
}
And now with your help, using attributes works wonders:
Document Model
protected $appends = [
'tomo_name',
'user_fullname'
];
public function getTomoNameAttribute()
{
return $this->tomo()->first()->name;
}
public function getUserFullNameAttribute()
{
return $this->user()->first()->first_name . ' ' . $this->user()->first()->last_name;
}
Document Controller
class Documents extends Controller
{
public function read(Request $request)
{
$provider = $request->only('id');
$documents = Document::select(['id', 'date', 'tomo_id', 'user_id', 'folio', 'description'])
->where(['provider_id' => $provider])
->orderBy('date', 'ASC')
->paginate(25);
return $documents;
}
}
And now it returns the data the way I expected
data […]
0 {…}
id 2
date 2018-12-01
tomo_id 1
user_id 1
folio 1
description 1
tomo_name 1
user_fullname First Last
Thank you so much!
try this
class Documents extends Controller
{
public function read(Request $request)
{
$provider = $request->only('id');
$documents = Document::select(['id', 'date', 'tomo_id', 'description'])
->with('tomo:id,name') // get relationship with id and name
->orderBy('date', 'ASC')
->paginate(25);
return $documents;
}
}
In your controller, try:
$documents->getCollection()->transform(function ($item) {
$item->tomo = $item->tomo->name;
return $item;
});
return $documents;
I'm encountering error like SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into buildings (building_name, updated_at, created_at) values (Building Four, 2017-10-12 02:56:13, 2017-10-12 02:56:13)). but i don't have a updated_at and created_at column in my database how come these columns shows up in the error?
BuildingRepository.php
<?php
namespace App\Repositories\Building;
use App\Building;
interface BuildingRepository
{
public function getById($id);
public function getAll();
public function create(array $attributes);
public function update($id, array $attributes);
public function delete($id);
}
EloquentBuilding.php
<?php
namespace App\Repositories\Building;
use \App\Building;
class EloquentBuilding implements BuildingRepository
{
private $model;
public function __construct(Building $model)
{
$this->model = $model;
}
public function getById($id)
{
return $this->model->findOrFail($id);
}
public function getAll()
{
return $this->model->all();
}
public function create(array $attributes)
{
return $this->model->fill($attributes)->save();
}
public function update($id, array $attributes)
{
}
public function delete($id)
{
}
}
BuildingController.php
<?php
namespace App\Http\Controllers;
use App\Building;
use Illuminate\Http\Request;
use App\Repositories\Building\BuildingRepository;
class BuildingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
private $building;
public function __construct(BuildingRepository $building)
{
$this->building = $building;
}
public function createBuilding()
{
return view('building.create');
}
public function store(Request $request)
{
$this->validate($request, array(
'building_name'=>'required',
'building_information'=>'required',
));
$buildings = array('building_name' => $request->building_name,
'building_inforamtion' => $request->building_information);
$this->building->create($buildings);
}
public function getAllBuilding()
{
$buildings = $this->building->getAll();
return view('building.show')->with('buildings', $buildings);
}
public function getSpecificRecord()
{
$buildings = $this->building->getById(1);
return view('building.show')->with('buildings', $buildings);
}
}
Building.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
protected $fillable = [
'id', 'building_name', 'building_information', 'building_image',
];
}
By default, Eloquent expects created_at and updated_at columns to exist in your tables. If you do not wish to have these columns to be automatically managed by Eloquent, then you need to set the $timestamps property in your model to false. Your file Building.php should look like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
public $timestamps = false;
protected $fillable = [
'id', 'building_name', 'building_information', 'building_image',
];
}
Yes, by default Eloquent expects created_at & updated_at columns in all your tables. You can set $timestamps property to false.
To make a column nullable, you mention that in your migration. For example, I want to make address column of my table nullable, I do this.
$table->string('address')->nullable();
I faced the same issue.
The problem was that the column name that I mentioned inside migration was not same as what I was using inside my controller, model and view.
So, I would suggest that you check whether you have taken same column name inside the migration that you are further using for mass assignment.
Turn places created_at and updated_at from the database
I tried to refrain myself from asking a stupid question once again, but here i am...
So i want to check if a ID in my pivot table (tutorial_id) matches another id. However, i have no idea how to to get this ID from the pivot table.. this is what i tried:
Controller:
class TagController extends BaseController {
public function getTutorials($tag) {
$tag_id = Tag::where('name', $tag)->first();
$tutorials = Tutorial::with('tags')->where('tutorial_id', '=', $tag_id->id)->get();
return View::make('tutorials/tags', array(
'tutorials' => $tutorials
));
}
}
Tutorial model:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function tags() {
return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
}
}
Tag model:
class Tag extends Eloquent {
protected $table = 'tags';
public function tutorials() {
return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
}
}
Database looks like this:
However i now get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tutorial_id' in 'where clause' (SQL: select * from `tutorials` where `tutorial_id` = 1)
So you want all tutorials with tag_id->id, you can do that like this: $tag_id->tutorials
I reformatted the code for you:
public function getTutorials($tag) {
$tag = Tag::where('name', $tag)->first();
return View::make('tutorials/tags', array(
'tutorials' => $tag->tutorials
));
}
reference: http://vegibit.com/many-to-many-relationships-in-laravel/