Query returning every row null in laravel - laravel

I'm trying to build a chat application using laravel echo and pusher, everything works but the data that returns to the databse is either null or the default value, here's the code
public function sendMessage(Request $request){
$conID = $request->conID;
$message1 = $request->message;
$user = Auth::user();
$fetch_userTo = DB::table('messages')
->where('conversation_id', $conID)
->where('user_to', '!=', Auth::user()->id)
->get();
$userTo = $fetch_userTo[0]->user_to;
$message = Message::create([
'user_from' => Auth::user()->id,
'user_to' => $userTo,
'conversation_id' => $conID,
'message' => $message1,
]);
if($message) {
$userMsg = DB::table('messages')
->join('users', 'users.id','messages.user_from')
->where('messages.conversation_id', $conID)->get();
broadcast(new MessagePosted($message))->toOthers();
return $userMsg;
}
}
NB: when i put insert() instead of create in the query the data goes through the database normally but there's an error in broadcasting

Have you tried to create a message like this? instead of using a model event?
$message = new Message;
$message->user_from = Auth::user()->id;
$message->$user_to = $userTo;
$message->conversation_id = $conID;
$message->message = $message1;
$message->save();
You have a lot more control this way, i.e
if($message->save()) { ... }
Or you could wrap the whole thing in a transaction?
Be sure your Message model allows the fields that you want to add in the $fillable array

Create method check fillable attributes into Laravel model. You have to write your all columns into fillable and then use create method.
Second solution is use Active Record technique. #Devin Greay answer is helpful to use Active record.
More information visit https://laravel.com/docs/5.6/eloquent#mass-assignment

Related

Update record using laravel

I have a question,
I have a form (view) and after submit it saves to the db.
one of the records is id.
when I open the form again for that ID and will press submit again
what will happened it will update the record? or try to create a new record and fail since id is primary key?
so it depends on your controllers etc if you have a updateController with the correct code it can be updated but you would also need a edit method as well, If you could share your code it will be easier to say what would happen instead of guessing
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:categories',
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Save','Success');
return redirect()->route('admin.category.index');
}
If you're trying to update record based on it's id then you could do this
public function update($request)
{
$user = User::firstOrNew([
'id' => $request->id
]);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->save();
}
It will find a record with that id, if none was found then create a new record with that id. This is just for example but you need to validate every request before update/insert.

Laravel Return Migration and Eloquent Response

Is there any way to get the response or message from the migration and eloquent? Regardless of success or failure.
Migration:
$response = Artisan::call('make:model', [
'name' => 'MyModel'
'-m' => true
]);
//I need the response for my next step
Eloquent:
$response = MyModel::create($myValues);
//I need the response for my next step
Use like this:
$myModel = new myModel();
$myModel->value = 'value';
$myModel->save(); // you can use create or other function here
Now your result is in $myModel. It's not related to migration.

How to queue the logics in controller

I have used two logic in my controller in my laravel project
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
$post = MyPost::create([
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
return redirect()->to('/admin/home);
}
Is it possible to make like if user is created successfully only then the post will be created so that I can use post created by user relationship
I have tried something like if condition but it is not working
You can try the code bellow , I assume you have a user_id field in posts table since you mentio9ned a relation ship. This is not the best way but i try to keep things simple, so I just edited the code.
Note : make sure you listed all the table fields in protected $fillable in your model before using Create()
public function multiStore()
{
$user = User::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=>Hash::make($request->name),
]);
if($user){
$post = MyPost::create([
'user_id' => $user->id
'name'=>$request->post_name,
'body'=>$request->post_body,
]);
}
return redirect()->to('/admin/home);
}
Enclose your query in database transaction
https://laravel.com/docs/5.8/database#database-transactions
Either you can:
DB::transaction(function() {
Model::create();
AnotherModel::create();
});
Or you can use the following to find and catch error...
DB::beginTransaction();
// Your queries here...
// Model::create();
// AnotherModel::create();
DB::commit();

Laravel 5.6 - Using model functions in ModelFactory

I am working with Laravel 5.6 and found myself a weird problem while extending the functionality of my project.
Right now i need to create two new models: order and item. It was quite easy to fill the items table with dummy data using Faker and Laravel Factories/Seeders. The biggest problem is while working with the order model.
This little fellow is related to a company with a foreign key named company_id and user with a foreign key named seller_id. The company field is okay, the trouble is behind my seller_id
This seller needs a role related to the company my factory will randomly pick for it because the user is not related to the company (directly) and i can't just look for it with a company_id.
In order to get all the users "related" to my company, i've created the next function on my Company model:
public function users()
{
$roles = $this->roles;
$users = [];
foreach ($roles as $role) {
foreach ($role->users as $user) {
$user->makeHidden(['pivot']);
array_push($users, $user);
}
}
$users = array_unique_objects($users);
return $users;
}
btw: I'm using laravel-permissions, a library made by Spatie.
What this functions does is get every role from a company and then it pushes it to an array of users.
This custom helper: array_unique_objects tracks any repeated user on my array and removes them.
That function works find because i've tested on a couple of controllers so i know there is no problem with it. Either way, my OrderFactory.php looks like this:
<?php
use Faker\Generator as Faker;
use App\Models\User;
use App\Models\Company;
$factory->define(App\Models\Order::class, function (Faker $faker) {
$company = Company::get()->random(1);
$users = $company->users();
$user = array_random($users);
return [
'company_id' => $company,
'seller_id' => $user->id,
'code' => strtoupper(str_random(10)),
'description' => $faker->sentence($nbWords = rand(2, 4), $variableNbWords = true),
'created_at' => $faker->dateTimeBetween($startDate = '-1 year', $endDate = 'now', $timezone = null)
];
});
But when i run the php artisan db:seed command, it throws the next error in console:
BadMethodCallException : Method Illuminate\Database\Eloquent\Collection::users does not exist.
at >/home/ironman/Documentos/Sandbox/Proventas/Backend/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:99
95| */
96| public function __call($method, $parameters)
97| {
98| if (! static::hasMacro($method)) {
99| throw new BadMethodCallException(sprintf(
100| 'Method %s::%s does not exist.', static::class, $method
101| ));
102| }
103|
Exception trace:
1 Illuminate\Support\Collection::__call("users", [])
/home/ironman/Documentos/Sandbox/Proventas/Backend/database/factories/OrderFactory.php:10
2 Illuminate\Database\Eloquent\Factory::{closure}(Object(Faker\Generator), [])
/home/ironman/Documentos/Sandbox/Proventas/Backend/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:274
Please use the argument -v to see more details.
Is there anything I can do to fix this problem? I know that using Laravel Relationships will fix my problem but the specifications of this project says that i have to keep things just as the are.
Your call to
$company = Company::get()->random(1);
does not return a single company. It returns a Collection, which does not have a users dynamic function. Try
$company = Company::get()->random(1)->first();

How to update column value in laravel

I have a page model. It has following columns in database table:
id
title
image
body
I want to update only "image" column value.
Here's my code:
public function delImage($path, $id) {
$page = Page::find($id);
$page->where('image', $path)->update(array('image' => 'asdasd'));
\File::delete($path);
}
it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
Version 1:
// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();
Version 2:
$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();
In case of answered question you can use them:
$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();
Try this method short and clean :
Page::where('id', $id)
->update(['image' => $path]);
An example from Laravel doc
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
DB::table('agents')
->where('id', $agentid)
->update(['status' => '0']);

Resources