Laravel update different database table - laravel

I have a controller in Laravel that is adding a 'room' to the database, like this...
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Room;
class SitesController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
/* Create Post */
$room = new Room;
$room->name = $request->input('name');
$room->save();
return redirect('/room')->with('success', 'Room Created');
}
}
This works great but I would also like to write something to a different database table. Am I locked in to only updating the 'rooms' table in this controller or is there a way to modify others?

You are asking
to write something to a different database table,
not into a totally different database, right?
Why would you think you are locked in? Just use another Model that represents the table you want to update as well.
use App\YourOtherModel;
...
/* Create Post */
$room = new Room;
$room->name = $request->input('name');
$room->save();
$other = new YourOtherModel;
... go ahead
$other->save();

Related

How to insert into two table using laravel 8? This is my code

This is my code
I have a table inventory_transactions(id, part_name, part_number) and transaction_logs(id, description, inventory_transaction_id(FOREIGN KEY)). I want to insert the value of id to inventory_transaction_id.
What should I do?
namespace App\Http\Controllers;
use App\Models\Inventory_transaction;
use App\Models\Transaction_log;
use Illuminate\Http\Request;
public function store(Request $request){
$inventory_transaction = $request->validate($this->validation());
$value = Inventory_transaction::create($inventory_transaction);
return $this->respondWithMessage('Transaction added');
}
private function validation()
{
return [
'part_name' => ['required'],
'part_number' => ['required'],
];
}
Assuming that you have relationships defined as
class Inventory_transaction extends Model
{
public function transaction_logs()
{
return $this->hasMany(Transaction_log::class);
}
}
you can use the relation to insert related record
public function store(Request $request)
{
$validated = $request->validate($this->validation());
$transaction = Inventory_transaction::create($validated);
$transaction->transaction_logs()->create(['description' => 'Transaction Added.']);
return $this->respondWithMessage('Transaction added');
}
Having said that you should seriously spend some time going through Laravel docs, it will enable you to understand the basics very well - Laravel has one of the best documentation with lots of code examples for easy understanding of basic
Laravel relations: https://laravel.com/docs/8.x/eloquent-relationships#introduction

Model:create used once but two rows created (laravel)

I was coding in my app and suddenly I realized that every create in my app makes two rows!
whenever I run model:create it makes two rows! it doesn't matter how or when I use a create method.
For example:
Route::get('test', function () {
\App\City::create([
'name' => 123,
'province_id' => 1
]);
});
obviously such code should create one row. but it creates two! I am stuck and don't know what to do!!
Update:
the city model is simple, but it doesn't matter what model I use.
But, running same code during interactive php artisan tinker session creates one row.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
public $timestamps = false;
protected $fillable = ['name' , 'province_id'];
public function province()
{
return $this->belongsTo('App\Province');
}
}

Laravel Record Update - Softdeletes record when updating the record

I have a basic CRUD of services. I've added the SoftDeletes in the model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Service extends Model
{
use SoftDeletes;
protected $table = 'services';
protected $fillable = [
'name','description',
];
}
When updating the record, I'm using the Laravel Eloquent, here is the code:
public function update(Request $request)
{
$this->validate($request, [
'name' => 'required',
]);
$service = Service::find($request->id);
$service->name = $request->name;
$service->description = $request->description;
$service->save();
}
Route in web.php is:
Route::post('service/update', 'ServiceController#update')
->name('updateService');
I don't know why this happens but every time I try to update a record, the deleted_at column is also updated (it is populated with the timestamp). What I want is that, the record will be updated not deleted.
PS
I've also tried it in other models that has SoftDeletes and the problem also occurs, the record is updated and then deleted.

Laravel class isn't in polymorphic relationship with other class

I am working on a polymorphic relationship between these classes in my small project: Submissions (same as posts), Comments and Users.
The problem is, I am able to gather all comments by relying on Submission model, for example:
$submissions = Submission::with('comments')->get()->find( $submission );
But, if I try something like this in tinker:
$users = User::with( 'comments' )->get();
I get all the users data, but no comments show up:
comments: Illuminate\Database\Eloquent\Collection {#3003
all: [],
},
Here's all the code of relations between models:
class Comment extends Model
{
protected $fillable = [ 'commentable_id', 'commentable_type', 'text' ];
public function commentable() {
return morphTo();
}
}
Now this is being added inside Submission and User model:
public function comments() {
return $this->morphMany( Comment::class, 'commentable' );
}
In Submission model I am using protected $guarded = []; to deal with Mass Assignment and I don't call it inside user model.
I hope you can tell me what am I doing wrong since somehow I can't access user model by comment model and vice versa.
Thanks in advance!
edit: Here's a code of creation of a comment:
public function store( Submission $submission ) {
$data = request()->validate([
'text' => [ 'required', 'string', 'max:255' ]
]);
$id = $submission->comments()->create([ 'text' => request()->text ]);
dd( $submission, $data );
}
Relation morphMany is one-to-many relation, like hasMany. So one comment can belong to a submission or a user, not both. One option is to create separate comments for submission and user (for the user do the same as for submission $user->comments()->->create([...])). Second option is to use many-to-many polymorphic relation, where one comment can belong to multiple submissions and users.

Laravel 5 - Inserting all POST data into database?

I'm using Laravel 5 and I created a resource controller, setup routing and setup my database model.
My question is: when I do a POST, my store method is called on the controller but how can I take the request data and insert a new entry in the db without having to explicitly set every field?
Here's my code:
public function store(Request $request)
{
$data = $request->all(); // this grabs all my request data - great!
$user = new User;
$user-> ??? // insert ALL posted data
$user->save();
}
I understand that I can do...
$user->name = $request->name;
...for every field. But can someone tell me how to insert everything?
I realize I can probably do a foreach but I'm wondering if there's something better.
There is method fill in every model https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_fill:
$user->fill($request->all());
Eventually you can use create:
\User::create($request->all());
This above is called mass asignment and there is section about this in Eloquents documentation https://laravel.com/docs/5.1/eloquent
You need to define which keys might be set:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// The attributes that are mass assignable
protected $fillable = ['name', 'login', 'birthdate'];
}

Resources