Add two queries at store method in controller - mysql

I have this migration table for OFFERS:
public function up()
{
Schema::create('offers', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('article_id')->unsigned();
$table->integer('price');
$table->string('comment');
$table->timestamps();
$table->string('key');
$table->string('title');
$table->timestamp('start');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('article_id')
->references('id')
->on('articles')
->onDelete('cascade');
});
}
Also this at model I have:
class Offer extends Model
{
//
protected $fillable = [
'price',
'comment',
'article_id',
'key',
'start'
];
protected $dates = [
'start'
];
public function setStartAttribute($date){
$this->attributes['start']= Carbon::createFromFormat('m/d/Y h:i a', $date);
}
public function getStartAttribute($date){
return (new Carbon($date))->toRfc2822String();
}
public function user(){
return $this->belongsTo('App\User');
}
public function article(){
return $this->belongsTo('App\Article');
}
}
Now at controller I have just store function:
public function store(Requests\OfferRequest $request)
{
$offer = new Offer($request->all());
Auth::user()->offer()->save($offer);
Alert::success('Offer is succesfully added!', 'Good job!')->persistent("Close");
return Redirect::back();
}
Now I also have the same model MAXOFFER. The same is migartion and model.
What I want to do is to add at OffersController store method a query that will chech does start excist in maxoffers table and if not then to add new row with data from request, but if excist row with same start value then to check price and if price is higher than current to update that row...
Please help me to rite that query inside store function at offercontroller...

The following query is created by guessing you have a relation maxoffer in Maxoffer model.
$maxoffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))->first();
if($maxoffer==null)
{
Ath::user()->maxoffer()->create($request->all());
}
else
{
if($maxoffer->price < $request->input('price'))
{
$newOffer = Auth::user()->maxoffer()
->where('address_id', $request->input('address_id'))
->where('start', $request->input('start'))
->update(['price'=>$request->input('price')]);
}
}

Related

Laravel One To Many (Inverse) / Belongs To return null

I use Laravel 8. I have 3 table. Course table, UserCourse, and User table. I want to get user courses. I tried it with tinker: Course::find(1)->user_courses -it works fine and give back me user_course.
UserCourse::find(1)->user_course - the problem is here, this will return me "null"
How can I get the User Courses?
Course table
Schema::create('courses', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
});
UserCourse table
Schema::create('user_courses', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
User table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
$table->timestamp('updated_at')->nullable();
$table->timestamp('created_at')->nullable();
});
Course.php
class Course extends Model
{
use HasFactory;
protected $fillable = [
'title',
];
public function user_courses()
{
return $this->hasMany(UserCourse::class);
}
}
UserCourse.php
class UserCourse extends Model
{
use HasFactory;
protected $fillable = [];
public function user_course()
{
return $this->belongsTo(Course::class);
}
}
Your database structure make it that the relation between course and user is a many to many relation with a pivot table in the middle.
Some correction you need to do for it to work seemingly with laravel conventions.
- The pivot table name should be course_user without a primary key
Schema::create('course_user', function (Blueprint $table) {
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->foreignId('course_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
- Remove the UserCourse.php model since it's a pivot
- Define the relation courses in User model as follow
User.php
public function courses()
{
return $this->belongsToMany(Course::class);
}
- Define the relation users in Course model as follow
Course.php
public function users()
{
return $this->belongsToMany(User::class);
}
Now to get any user courses, just run User::find(1)->courses
Same thing to get the users that belongs to the same couses Course::find(1)->users
get courses that the user has not taken:
$userId = 1;
$courses = Course::whereDoesntHave('users', function($userQB) use($userId) {
$userQB->where('id',$userId);
})->get();

Laravel Eloquent trying to retreive all answers with the same foreign key in a table

I have a project in which I have 3 tables a questions table an answers table and a users table
In the Questions table I have the following:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->string('question');
$table->timestamps();
});
In the Users table I have the following:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('district')->nullable();
$table->string('area')->nullable();
$table->string('committee')->nullable();
$table->string('position')->nullable();
$table->rememberToken();
$table->timestamps();
});
In the Answers table I have the following:
Schema::create('answers', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedBigInteger('question_id');
$table->foreign('question_id')->references('id')->on('questions');
$table->string('answer');
$table->timestamps();
});
And those are the models
class Answer extends Model
{
public function user(){
return $this->hasOne('App\User');
}
public function question(){
return $this->hasOne('App\Question');
}
}
class Question extends Model
{
public function answer(){
return $this->hasMany('App\Answer');
}
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','district','area','committee','position',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function answer(){
return $this->hasMany('App\Answer');
}
}
Based on my structure the answers table will have entries with each row made of the user_id and his answer to one question and in the following row the other question
How can I retrieve the data in a table where it shows me in the first row the user in a column with all 4 of his answers in the following 4 columns?
First Answer model should be like this. As it's one-to-many.
class Answer extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function question(){
return $this->belongsTo('App\Question');
}
}
And then you can get data like this:
$results = User::with('answer')->first();
// this should give the first `user` with all the answers that belongs to the user.
$results = User::with('answer')->get();
// this should give you all the users.
let's say you need all users and all the answers.
foreach ($results as $user) {
echo $user->name;
foreach ($user->answer as $value) {
echo $value->answer;
}
}
Let me know if it helps.

Laravel SQLSTATE[42S22]: Column not found: 1054 Unknown column

I am trying to make a relationship with lecturers table and users table. So this is the code of create_lecturers_table
public function up()
{
Schema::create('lecturers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('class03');
$table->integer('class03_stream');
$table->date('class03_from');
$table->date('class03_to');
$table->string('remarks')->nullable();
$table->integer('created_user_id')->unsigned()->nullable();
$table->integer('updated_user_id')->unsigned()->nullable();
$table->foreign('created_user_id')->references('id')->on('users');
$table->foreign('updated_user_id')->references('id')->on('users');
$table->timestamps();
});
}
This is the Lecturer model
class Lecturer extends Model
{
protected $table = 'lecturers';
protected $fillable = [
'class03', 'class03_stream' ,'class03_from','class03_to','remarks','created_user_id','updated_user_id',
];
public function user(){
return $this->hasMany('PMS\User');
}
}
This is the lecturer index function of the controller
public function index(Lecturer $model)
{
return view('lecturers.index',['lecturers' => $model->paginate(15)]);
}
This is the create_users_table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('user');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('usertype');
$table->boolean('activestatus')->default(false);
$table->rememberToken();
$table->timestamps();
});
}
This is the User model
class User extends Authenticatable
{
use Notifiable;
public function lecturer(){
return $this->belongsTo('PMS\Lecturer');
}
protected $fillable = [
'name', 'email', 'password','usertype',
];
With this what I wants to do is to view the User's name who will create the lecturer via System.So that I have echo the user's name as below in the view.blade.php
<td>{{ $lecturer->user->name }}
When I go to the view it generate this error.
ErrorException (E_ERROR)
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.lecturer_id' in 'where clause' (SQL: select * from `users` where `users`.`lecturer_id` = 1 and `users`.`lecturer_id` is not null) (View: E:\BIT FINAL YEAR PROJECTS\20190419-using-template\resources\views\lecturers\index.blade.php)
Could someone please tell me what is the wrong .
Thanks
I think you have your Eloquent relationships the wrong way around. Try changing them to as follows:
Lecturer
public function user(){
return $this->belongsTo('PMS\User', 'created_user_id');
}
User
public function lecturers(){
return $this->hasMany('PMS\Lecturer', 'created_user_id');
}

How to delete a user and automatically all his relations using 'cascade'?

I'm trying to delete a user and automatically all his relations using 'cascade'. Not sure how to do it. I'm using mysql.
So far i've made this:
User Model
class User extends Authenticatable
{
use Notifiable;
//...
public function profile()
{
return $this->hasOne('App\Profile');
}
}
Profile Model
class Profile extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
Profile migration
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->integer('phone');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
And with tinker I'm tryng to do:
$user = App\User::firsts();
$user->delete(); // it deletes only the user
$user->profile->delete(); // it deletes only the profile
You could make use of Model Events:
class User extends Eloquent
{
public static function boot ()
{
parent::boot();
self::deleting(function ($user) {
// This will be executed right before the user is deleted
$user->profile->delete();
});
}
}
This way, whenever you call the delete() method on a User object, Laravel will fire the $user->profile->delete(); right before.
Rather than a database cascade you could delete the related model when the user is deleted by deleting the related model using the deleting event.
Include this in the Boot function of the User Model:
public static function boot ()
{
parent::boot();
self::deleting(function (User $user) {
$user->profile->delete();
});
}
Theres no need to do relationship staff for working with cascade. This code works fine for me -
Migration:
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->integer('phone');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Controller:
Here ->delete() can delete both user and profile row
public function deleteUser(){
Auth::user()->delete();
return redirect()->back();
}
View Delete Link
Delete
Route
Route::get('/delete', 'HomeController#deleteUser')->name('deleteUser');

Laravel 5.4 foreign key relation show null in table

I am trying to save the Client and device foreign keys in my inquiry table but somehow it keeps returning null(my Migration for that is nullable). I get no Errors if I return $Client or $device it Returns a correct id.
This is how the Controller Looks like:
# foreign key in this table rreturns null InquiryController
public function store(Request $request)
{
$input = $request->all();
$client = Client::find($request->input('client_id'));
$device = Device::find($request->input('device_id'));
$stream = new Stream;
$stream->stream_name = $request->input('stream_name');
$stream->save();
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);
$inquiry->save();
}
And this is my Inquiry Model
class Inquiry extends Model
{
protected $table = 'inquiries';
protected $fillable = ['user_id', 'client_id', 'device_id', 'stream_id'];
# relations
public function user()
{
return $this->belongsTo(User::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
public function device()
{
return $this->belongsTo(Device::class);
}
public function stream()
{
return $this->belongsTo(Stream::class);
}
}
this is the relation function for the Client and device model:
public function inquiry()
{
return $this->hasMany(Inquiry::class);
}
The Migration:
public function up()
{
Schema::create('inquiries', function(Blueprint $table)
{
$table->increments('id');
$table->unsignedInteger('client_id')->nullable();
$table->unsignedInteger('device_id')->nullable();
$table->timestamps();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('inquiries');
}
Make sure you have your foreign keys defined in the migration for the inquiry table.
For example:
$table->integer('client_id')->unsigned();
$table->foreign('client_id')
->references('id')->on('clients')
->onDelete('cascade');
Update:
Try saving the model before adding the relationships. Swap it around to:
$inquiry = new Inquiry;
$inquiry->fill($data);
$inquiry->save();
$inquiry->client()->associate($client);
$inquiry->device()->associate($device);
$inquiry->stream()->associate($stream);