What is the best way to assign a user ID - Laravel - laravel

I'm creating an advert like this
public function store(Request $request)
{
$advert = PropertyAdvertisement::create($request->all());
return response()->json($advert);
}
What is the best way to attach a user_id on the advert model?

After creating, add a line before the return to give the field to the $advert variable (assuming user_id is a fillable field on the PropertyAdvertisement model and your request is routed through the Auth middleware):
$advert->user_id = \Auth::user()->id;
$advert->save();
Or if you want less code, add the user_id to the $request object in advance of creation:
$request['user_id'] = \Auth::user()->id

Related

How to get only selected column in a child related model?

I have two models, User and Post, where a User can have multiple Post models. In my application, I only want to retrieve the title column from the related Post model when querying for a User. Here is my current code:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Here is what I have tried to retrieve the title column for the related Post models:
$user = User::with('posts:title')-\>get();
However, this retrieves all the columns for the Post model. How can I modify my code to only retrieve the title column for the related Post models? Thank you!
try this
$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();
If you want to get the data with selected column you also need to pass the FK to identify its relationship.
The example below tells the the post also need the user_id column to identify the relationship between POST and USER model
$user = User::with('posts:title,user_id')->get();

Model Relationships not finding the property

I'm trying to create a relationship between two models. My first model is the User Model, the second one is Company.
I tried adding in the User model the hasMany('App\Comapny') property, and in the Company one, belongsTo('App\User').
// In User Model
public function companies(){
return $this->hasMany('App\Company');
}
// In Company Model
public function user(){
return $this->belongsTo('App\User');
}
// And in the controller:
$user_id = auth()->user('id');
$user = User::find($user_id);
return view('devices.show')->with('companies', $user->companies);
It should return an array with all the companies that my User has when using "$user->comapnies", however, it returns this message instead:
Property [companies] does not exist on this collection instance.
Thanks, any help is welcome
Thanks for the quick response. I figured it out, the problem was this line:
$user_id = auth()->user('id');
It should be instead
$user_id = auth()->user()->id;
Try this,
$user_id = auth()->user->id;
$user = User::with('companies')->where('id', $user_id)->first();
return view('devices.show', compact('user'));
Then you can access the company relation with
$user->company[index]->
in the view.

Accessing data trough relationship Laravel

I have two tables/models. User and Advert.
When a user posts an advert their userid is a column in the database row. I want to use the id to get the user details and show it in a blade template.
These are the models
Advert belongs to a user.
class Advert extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
User has many adverts.
class User extends Authenticatable
{
public function advert(){
return $this->hasMany('App\Advert);
}
}
On the advert show page I want the users name and details printed out beside it. Currently I can only access the ID as that is stored as a attirbute in the advert column in the DB. How can I use this relatonship to access the users data.
This is the show controller
public function show($id){
//Shows add user clicked on based on id
$user = User::where('id', $id)->first();
$Advert = Advert::where('id', $id)->first();
return view('pages/advert/show', compact('Advert', 'user'));
}
In the show page view I can access the user id like so {{$user->id}}
You are using the $id passed into your show function for retrieving both the user and the advert.
public function show($id){
// Get the avert with the passed in id
$advert = Advert::find($id);
// From the advert get the user related to it.
$user = $advert->user;
return view('pages/advert/show', compact('advert', 'user'));
}
Take a look at https://laravel.com/docs/5.6/eloquent-relationships#querying-relations to get a better understanding of how eloquent works with relationships.

detach() in pivot table

Can't figure out how to delete record from pivot table.
I have users that belongsToMany documents with pivot document_user table.
here is my attach method:
public function share(Request $request, $company_id, $id)
{
$document = Document::find($id);
$user = $request['user'];
$document->users()->attach($user);
flash('Document has been shared!');
return back();
}
But how to make detach function? Should I build a form for this and what function should be? Something like $document->users()-detach($user). I have tried this, but doesn't work
You can do this in a couple ways:
First, you can use the detach() functionality (requires a second function in your controller). An example using a similar format to the one you provided:
public function unshare(Request $request, $id)
{
$document = Document::findOrFail($id);
$userId = $request['user']; //Assuming this is the User ID
$user = User::findOrFail($userId);
$user->documents()->detach($document->id);
flash('Document has been detached!');
return back();
}
Second, you can create a single function that toggles the association. Essentially you send a Document ID and if it is already associated to the User then it is Detached, if it is NOT associated to the User then it will Attach.
public function share(Request $request, $id)
{
$document = Document::findOrFail($id);
$userId = $request['user']; //Assuming this is the User ID
$user = User::findOrFail($userId);
$user->documents()->toggle($document->id); //This can also be an array of IDs
flash('Document has been toggled!'); //You might want to pass something or look up the association if you want custom messaging for attach or detach
return back();
}
Hope this helps!

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