Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

Have a look at this http://laravel.com/docs/eloquent#inserting-related-models. You can define the client_id like you said using:

$project = new Projects();
$project->name = Input::get('name');
$project->client_id = 1;
$project->save();

But you can also do it, using the client model:

$client = Clients::find(1);

$project = new Projects();
$project->name = Input::get('name');
$project->client_id = $client->id;
$project->save();

And last, but not least, also my preferred one:

$client = Clients::find(1);

$project = new Projects();
$project->name = Input::get('name');

$client->projects()->save($project);

And a little side-note, I prefer to name my models not as plural but as single like "Project" and "Client". When you name it singular you can never get confused with collections and models.

Last updated 2 years ago.
0

That's my problem, I don't want to add a project with client_id 1, I want to add the clients id that was clicked from the previous page. Let's say that there is a foreach in www.example.com


@foreach($clients as $client)
         {{ HTML::linkRoute('client',$client->url_client,array($client->url_client))}}
@endforeach

and when i click them it gets me to www.example.com/client1, www.example.com/client2.... So how can I get the id which belongs to that specific client?

Last updated 2 years ago.
0

You can use the ID in your Route, then it's just the parameter of the function.

For example, if I want to see all clients, there should be an url like this: www.example.com/clients. And for a individual client, you can do something like this: www.example.com/clients/1.

Please take a look at http://laravel.com/docs/routing#route-parameters for using parameters in your routes. Eventually you can create a route function like this:

public function create( $id )
{
    $client = Clients::find($id);
    
    if( empty($client) )
        return "Could not find client #". $id;

    $project = new Projects();
    $project->name = Input::get('name');

    $client->projects()->save($project);

    return "Project #". $project->id ." created for client #". $client->id;
}
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

eugael eugael Joined 25 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.