is it possible to save more data than just the id's to a many-to-many pivot?
My Code:
public function lists() {
return $this->belongsToMany('ShoppingList','shopping_list_ingredients','shopping_list_id','ingredients_id')
->withPivot(array('unit','amount'))
->withTimestamps();
}
and vice verca!
And now, I need to add the additional data to the pivot.
This is my saving code:
$list = new ShoppingList;
$list->user_id = Auth::user()->id;
$list->title = Input::get('recipe_title');
$list->save();
$list->ingredients()->sync(Input::get('ingredient'));
$list->push();
and my view code:
- {{$i->amount}} {{$i->unit}} {{$i->name}} - {{ Form::checkbox('ingredient[]', $i->id) }}<br/>
Now I need somehow pass the "amount" and "unit" for each ID into the controller and into the pivot. Right now, it only saves the IDs.
How can I do it?
You have to use the attach function.
$list->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
You may try something like this:
$ingredientId = Input::get('ingredient');
$amount = 'some amount';
$unit = 'some unit';
$pivotData = array($ingredientId => array('amount' => $amount, 'unit' => $unit));
$list->ingredients()->sync($pivotData);
You may also use attach method, read the documentation on Laravel Website for more information.
Related
i need the code that will enable me fetch an entire table from the database and load it to my view. and also to the code that will display the item in my views
my controller:
public function index()
{
if(Auth::user()->usertype=='Admin')
{
$categories_count = Categories::count();
$news_count = News::count();
$published_news = News::where('status', 1)->count();
$unpublished_news = News::where('status', 0)->count();
$slider_news = News::where('slider_news', 'yes')->count();
$slidsder_news = News::where('slider_news', 'yes')->count();
$featured_news = News::where('featured_news', 'yes')->count();
$editor = User::where('usertype', 'Editor')->count();
}
else
{
$user_id=Auth::user()->id;
$news_count = News::where(['user_id' => $user_id])->count();
$published_news = News::where(['user_id' => $user_id, 'status' => '1'])->count();
$unpublished_news = News::where(['user_id' => $user_id, 'status' => '0'])->count();
}
return view('admin.pages.dashboard',compact('categories_count','news_count','published_news','unpublished_news','slider_news','featured_news','editor'));
}
You can simply do
Model::all();
To get all the data for that model/table. I would recommend paginating this if you have large data sets like so:
Model::all()->paginate(20);
See pagination here.
Once you have this assigned to a variable, as you already have done, you can pass it into your compact.
Within your view, it's always worth checking the collection isn't empty before attempting to loop over:
#if ($exampleItems->isNotEmpty())
and then you can continue to loop over the collection:
#foreach ($exampleItems as $exampleItem)
I recommend learning the basics using various tutorials such as Laracasts because if I've understood your request, this is fairly basic.
I am creating a web site. So , I have stored data in the database. Now I want to view data from two different tables. Then I tried a method like below. But , it gives me this error -
Trying to get property 'firstname' of non-object (View: D:\wamp64\www\cheapfares\resources\views\invoices\des.blade.php)
But , clearly firstname is in the database table.
How can I Fix this ??
Controller page. ( InvoicesController.blade.php )
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
$twoar = [];
$twoar['inv'] = $invoice;
$twoar['trms'] = $tr;
return view('invoices.des', ['twoar' => $twoar]);
}
View page. ( des.blade.php )
{{$twoar['inv']->firstname}}
{{$twoar['trms']->topic}}
Route.
Route::get('/invoice/adminuser-invoice/{invoiceno}', [
'uses' => 'InvoicesController#adminuserinvoice',
'as' => 'invoice.adminuser'
]);
Although casting the response to Array might be a suitable solution, the cause of your exception most likely lies in not having a valid entry in the database.
You can improve your code like this to mitigate that:
public function userinvoice($terms, $invoiceNo)
{
// Load invoice, or throw ModelNotFoundException/404 without valid entries.
$invoice = Invoice::where('invoicereference', $invoiceNo)->firstOrFail();
// load the terms.
$terms = DB::table('termsandconditions')
->where('topic', $terms)->first();
return view('invoices.des', compact('invoice', 'terms'));
}
In this example I made $terms and $invoiceNo obligated arguments in the route. To ensure the query will provide proper results. In addition an Invoice entry is now required with firstOrFail(), the terms is optional. Instead of assigning both variables to an array, I'm sending them both to the view so you can assert their value properly without cluttering using array key access.
Your view:
{{$invoice->firstname}}
{{$terms->topic}}
Try this below code:
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
return view('invoices.des', ['tr'=>$tr,'invoice'=>$invoice]); //Directly pass the mulitple values into the view
}
And your view page like this:
{{$invoice->firstname}}
{{$tr->topic}}
Its may help for you friend.
This is the scenario. I've User A that send via notification to other User B,C,D... a request to join a group. So in laravel I've created the migration and the controller to handle the notification.
This is the code of GroupController
...
foreach ($userINList as $userIN) {
$userIN = str_replace(' ', '', $userIN);
$userDBList = User::all();
foreach ($userDBList as $userDB) {
$name = $userDB->last_name . $userDB->first_name;
$name = str_replace(' ', '', $name);
if (strcmp($name, $userIN) == 0) {
$newGroup->users()->attach($userDB->id, ['role' => 'member', 'state' => 'pending']);
$notification = User::find($userIN->id);
$notification->notify(new GroupNotification($newGroup));
}
}
}
...
So in $notification I'll try to pass the id of Users that receive the invite and then I use the notify() method to send the notification, but after User A created the group and there aren't notifications to User B, C, D...
I've included the use Notifiable in group model. So what's the problem? What I've have to do.
Thanks
As far as I can tell from the code you're doing the following:
There is an array of names in the $userINList variable
You loop through each of the names in the array
Remove all spaces in the name
Retrieve every User
Loop through each User
Remove all the spaces in the User's name
Compare the 2 names
If the comparison passes then you add the User to the group and send a notification
There are quite a few improvements we can make here. For example, we already know which users you wish to notify so you do not need to fetch and compare all users.
Firstly, $userINList should either be an array of User objects or an array of User ids — an array of User objects is better. Then you can simply iterate through each one.
For example, if you have an array of ids then you could do this:
$group = Group::find(1);
$userINList = [1, 2, 3, 4];
User::whereIn('id', $userINList)
->get()
->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
And if you had an array of objects it would be even easier, you could do this:
$group = Group::find(1);
collect($users)->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
Super simple :-)
I need to get the record with special id and i have this in my method :
public function addedMark()
{
$user = Auth::user();
$subject = ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id');
return view('educator.account.marks', [
'user' => $user,
'marks' => StudentMark::where('subject_id', $subject)->get()
]);
}
When i do dd(ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id')); i see that I'm getting the information that i need, but when i do dd(StudentMark::where('subject_id', $subject)->get()); it returns an empty array.
Any idea why?
Change it to (whereIn)
'marks' => StudentMark::whereIn('subject_id', $subject)->get()
and let see what hapens
In $subjectyou have id and subject_id. You might wanna just take subject_id.
So change this: StudentMark::where('subject_id', $subject)->get()
to
StudentMark::where('subject_id', $subject[1])->get()
In some part of my app I need to update only the field is_active of some table with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
And if you want to update particular row only , use this:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= abc#gmail.com; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
This will work:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
When you don't want callbacks to be triggered, just use updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here table with a new value for is_active column.
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
I faced this issue when upgrading my project from 2.10 to 3.x.
In 2.10 you could update a single field using:
$this->Menus->saveField('css', $menucss);
But since this method was deprecated, we do as below now, considering that callbacks will not be triggered:
$this->Menus->updateAll(['css' => $menucss], ['id' => $menu_id]);
The other answers don't use internationalization and other models props, callbacks, etc.
I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}