Insert multiple values on multiple rows - laravel

I have a form that has a dropdown where the user can select up to 5 countries.
I have two related tables, users and countries, where each user can have multiple countries selected.
The users table:
+----+----------+----------------------+
| id | username | description |
+----+----------+----------------------+
| 1 | user1 | Some description. |
| 2 | user2 | Another description. |
+----+----------+----------------------+
The countries table:
+----+---------+---------------+
| id | user_id | country |
+----+---------+---------------+
| 1 | 1 | Canada |
| 2 | 1 | United States |
| 3 | 1 | France |
| 4 | 2 | Spain |
| 4 | 2 | Italy |
+----+---------+---------------+
As you can see, the country dropdown values should each have their own row in the table.
Here is my UserController so far (it only inserts into the users table for now):
$user = new User;
$user->username = Input::get('username');
$user->description = Input::get('description');
$user->save();
How would I insert multiple dropdown values such that each has its own row? What should my models look like for this to work?

If you're gonna use eloquent to do it, here's a suggestion:
//in your User model
public function countries()
{
return $this->hasMany('Country');
}
//insert from the controller
$countries = json_decode(Input::get('countries'), true); //assuming you use json to submit the multiple countries
$user_countries = array();
foreach($countries as $country)
{
$user_countries[]=new Country(array('country'=>$country));
}
//save the countries into the DB
$user->countries()->saveMany($user_countries);
for more info, do refer to the documentation:
http://laravel.com/docs/4.2/eloquent#inserting-related-models

Related

Laravel Copy record and duplicate with User IDs

How can i copy a record and save it with a different value for 1 or more field? for example
I have a table(post table) with following columns - ID | User ID | Post Title | Post Type
And User Table(user) with following columns - ID | Username | Email | Password
What i need to do is - When the saving post data needs to be duplicate with user ids
For example - In user table there is 10 users and when i save the post it should be duplicate for all ten user id
ID | User ID | Post Title | Post Type
1 | 1 | Test Post | Public
2 | 2 | Test Post | Public
3 | 3 | Test Post | Public
4 | 4 | Test Post | Public
5 | 5 | Test Post | Public
6 | 6 | Test Post | Public
7 | 7 | Test Post | Public
8 | 8 | Test Post | Public
As suggested, you can do this using model replication. Like
$post = Post::find(12892); //change with your id.
// get all the users.
$users = User::all();
foreach($users as $user){
$newPost = $post->replicate();
$newPost->user_id = $user->id;
// save post.
$newPost->save();
}

BelongsToMany by array values in laravel

How do I store data in users.sport_id:
User class:
public function sport() {
return $this->belongsToMany('App\Sport');
}
Where sports table has:
+----+------------+
| id | sport |
+----+------------+
| 1 | baseball |
+----+------------+
| 2 | basketball |
+----+------------+
Do I add to user.sport_id = 1,2 or save it as array [1,2] and use $casts = ['sport_id'=>'array'];

How can I get a post with all related ones?

Here is my table structures:
// tickets
+----+------------+----------------------+--------+---------+
| id | subject | content | closed | user_id |
+----+------------+----------------------+--------+---------+
| 1 | subject1 | question1 | 0 | 123 |
+----+------------+----------------------+--------+---------+
// answers
+----+----------------------+---------+-----------+
| id | content | user_id | ticket_id |
+----+----------------------+---------+-----------+
| 1 | answer1 | 123 | 1 |
| 2 | answer2 | 456 | 1 |
+----+----------------------+---------+-----------+
Now I need to get a ticket with along all its answers. I can do that using pure SQL like this:
SELECT t.*, a.*
FROM tickets t
LEFT JOIN answers a
ON t.id = a.ticket_id
WHERE t.id = ?
Now I'm using Laravel and I want to do that using with() class (however not sure it is possible). Any idea what change should I make in the models for doing that?
Noted that I can get just a ticket in Laravel like this:
$ticket = Tickets::where('id', $request->id)->get();
First make a hasMany() relationship in your Tickets model class.
public function answers()
{
return $this->hasMany(Answers::class, 'ticket_id', 'id');
}
And then in your controller query
$tickets = Tickets::with('answers')->where('id', $request->id)->get();

Laravel. How to get relationships where foreign key is an array

I am trying to retrieve database rows with their relationships. However, the local key is an array. Let me explain using an example.
Lets say I have a table of countries and a table of pages. Each country can have many pages. Each page can belong to multiple countries. I do not have the flexibility to change this schema.
pages
+-------------+-----------+
| id | name | countries |
+-------------+-----------+
| 1 | Page 1 | 1 |
+-------------+-----------+
| 2 | Page 2 | 1,2,3 |
+-------------+-----------+
| 3 | Page 3 | 4,5,6 |
+-------------+-----------+
countries
+----+----------------+
| id | name |
+----+----------------+
| 1 | United States |
+----+----------------+
| 2 | United Kingdom |
+----+----------------+
| 3 | Germany |
+----+----------------+
| 4 | France |
+----+----------------+
| 5 | Hong Kong |
+----+----------------+
| 6 | Thailand |
+----+----------------+
| 7 | Belgium |
+----+----------------+
| 8 | Singapore |
+----+----------------+
My model and controller look something like:
country
public function pages()
{
return $this->hasMany(Page::class, 'id', 'countries');
}
MemberController.php
$countries = Country::with('pages')->get();
This is returning all countries, but only Page 1 contains any relationships.
Is there a way to retrieve relationships using a whereIn approach so all three countries will return appropriate pages?
Thanks in advance
Since Page can belong to many Countries, you need to create a pivot table called country_page and remove the countries column.
Then define two belongsToMany() relationships in both models:
public function pages()
{
return $this->belongsToMany(Page::class);
}
If you're not following Laravel naming conventions listed in my repo and you gave the pivot name a custom name, define it too:
public function pages()
{
return $this->belongsToMany(Page::class, 'custom_pivot_table');
}
Something like this ?
$datas = Pages::where( ##your conditions### )->get()->inArray();
$countries = Countries::pluck('name','id'); // return array of id=>name
foreach($datas as $key=>$data) {
$c = [];
foreach(explode(',',$data['countries']) as $country_id) {
$c[]=$countries[$country_id];
//or
$c[]= ['id'=>$country_id,'name'=>$countries[$country_id]];
}
$datas[$key]['countries']= $c;
}

Laravel 5 - Eloquent JOIN confusion

I have two simple tables, cats and breeds:
mysql> select * from cats;
+----+--------+---------------+----------+---------------------+---------------------+
| id | name | date_of_birth | breed_id | created_at | updated_at |
+----+--------+---------------+----------+---------------------+---------------------+
| 1 | Rita | 2008-07-06 | 1 | 2015-05-09 20:40:49 | 2015-05-09 20:50:20 |
| 2 | Muni | 1992-05-15 | 3 | 2015-05-09 20:50:54 | 2015-05-09 20:50:54 |
| 3 | Hector | 2005-01-23 | 4 | 2015-05-09 21:08:23 | 2015-05-09 21:08:23 |
+----+--------+---------------+----------+---------------------+---------------------+
3 rows in set (0.00 sec)
mysql> select * from breeds;
+----+------------+
| id | name |
+----+------------+
| 1 | Domestic |
| 2 | Persian |
| 3 | Siamese |
| 4 | Abyssinian |
+----+------------+
4 rows in set (0.00 sec)
All I want to do is get a list of the cats that are of a certain breed. In the cats table, breed_id is a FK that points to the PK of the breeds table. The example code in my book which is supposed to return a view with all cats of a specific breed returns no results:
The url I am trying is /cats/breeds/Domestic
The view that is generated uses this logic in the routes.php file:
Route::get('cats/breeds/{name}', function($name)
{
$cats = Furbook\Cat::with('breeds')
->whereName($name)
->get();
dd($cats);
});
When I dd($cats) I get zero results even though I have a cat with a domestic breed_id of 1. What have I done wrong here?
EDIT:
I can get it to work with the following hacky code, which first gets the id from the breeds table by querying against the name field, then queries the cats table with that id:
$breed = Furbook\Breed::whereName($name)->get();
$id = $breed[0]['attributes']['id'];
$cats = Furbook\Cat::whereId($id)->get();
How do I make this into one Eloquent query? I see no examples for this kind of query on the Laravel site.
For more information this is how the models look:
class Breed extends Model {
public $timestamps = false;
public function cats()
{
return $this->hasMany('Furbook\Breed');
}
}
class Cat extends Model {
protected $fillable = [
'name',
'date_of_birth',
'breed_id',
];
public function breed()
{
return $this->belongsTo('Furbook\Breed');
}
}
You're asking the system to give you all cats with a name of Domestic - not all cats of the breed name Domestic.
Assuming your model relationships are in order, you could do e.g.
$cats = Furbook\Breed::whereName($name)->first()->cats;
Also, my Burmese cat just hit the monitor; I think she's upset that she's not in the breeds list.

Resources