Laravel - User validation id giving wrong response - laravel

I have this code in Laravel-8:
$userId = Auth::user()->id;
$companyId = Auth::user()->company_id;
$confirmUser = User::where('company_id', $companyId)->where('active', 1)
->where(function ($query) use($request) {
$query->where('email', $request->email);
})->whereNull('deleted_at')->first();
if(!$confirmUser){
return $this->error('The User already exists', 400);
}
If user already exists, I want to:
return $this->error('The User already exists', 400);
carry on with the operation.
dd($confirmUser); gives null
Yet the postman response is:
{"message":"The User already exists","error":true,"code":400}
How do I resolve this?
Thanks

$userId = Auth::user()->id;
$confirmUser = User::where('company_id', Auth::user()->company_id)->where('active', 1)
->where('email', $request->email)->whereNull('deleted_at')->first();
if($confirmUser){
return $this->error('The User already exists', 400);
}

Related

Laravel 6 - validate unique, ignore on two conditions - same user and name. Also $this->id is null on update

I have the following rule so far.
$rules['name'] = [
'required',
'string',
'min:3',
'max:255',
Rule::unique('user_templates', 'name')->ignore($this->id),
];
Users can create records, but all his records must have a unique name (other users can have records with the same name). How can I do this? Also, $this->id on update is always null. What am I doing wrong?
Controller
public function update(UserTemplatesRequest $request, $slug)
{
try {
$model = UserTemplates::where('slug', XSS::clean($slug))
->firstOrFail();
} catch (ModelNotFoundException $err) {
return redirect()->action('UserTemplatesController#index');
}
$data = $request->validated();
if ($model->updateTemplate(XSS::clean($data, ['file']), $request)) {
$message = "There was an error, please try again";
$action = 'index';
$id = '';
} else {
$message = "Category Updated";
$action = 'edit';
$id = $model->id;
}
return redirect()->action("CategoriesController#{$action}", [$id])
->with('message', $message);
}
According to your Rule you can try and use a where clause to narrow it down to one user and not whole project like:
Rule::unique('user_templates', 'name')->where(function (Builder $query) {
return $query->where(
'user_id', '=', $this->user()->id;
})
user_id is the column inside your user_templates table that works as a foreign key with your users table.
About $this->id it should be $this->user()->id to retrieve your user id

Sending email passing name in laravel

I'm trying to send an email to a user by entering his name and I look for the user's email with this name, but it does not work, the success message appears but in my email I receive nothing. what am I doing wrong?
if(User::where('name', '=', $destinatario)->exists()){
$exists = DB::table('users')
->select('email')
->where('name', $destinatario)
->get();
Mail::to($exists)->send(new TestEmail($remetente, $nome, $assunto, $exists, $mensagem));
return back()->with('sucess', 'Message sent!');
}else{
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
//$address = 'gabriel.jg04#gmail.com';
$subject = 'E-mail de Usuário';
$name = 'Juelito';
return $this->view('emails.test',['texto'=>$this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario, $name)
->subject($this->assunto);
}
Problem is with get(). get() returns collection of users.
But your mailable expect single user.
If you want to send mail to one person you could do like that:
$user = User::where('name', '=', $destinatario)->first();
if($user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
If you want to send mail to multiple persons you could do like that:
$users = User::where('name', '=', $destinatario)->get();
if($users->count()){
foreach($users as $user){
Mail::to($user)->send(new TestEmail($remetente, $nome, $assunto, $user, $mensagem));
}
return back()->with('sucess', 'Message sent!');
} else {
return back()->with('error', 'User does not exist!');
}
Mailable:
public function __construct($remetente, $nome, $assunto, $destinatario, $data)
{
$this->remetente = $remetente;
$this->nome = $nome;
$this->assunto = $assunto;
$this->destinatario = $destinatario;
$this->data = $data;
}
public function build()
{
return $this->view('emails.test', ['texto' => $this->data])
->from($this->remetente, $this->nome)
->replyTo($this->destinatario->email, $this->desctinario->name)
->subject($this->assunto);
}

Using with() and find() while limiting columns with find cancels relation data

I have the following code that displays different data depending on if you are the authenticated user looking at your own data or if you are looking at data from another user. The code works but in my opinion is very nasty.
public function showUserDetailed(Request $request, $username)
{
$key = strtolower($username).'-data-detailed';
if(Auth::user()->usenrame === $username) {
$key = $key .'-own';
}
if(Cache::has($key)) {
if($request->wantsJson()) {
return request()->json(Cache::get($key));
} else {
return view('user/detailed', ['user' => Cache::get($key)]);
}
} else {
if(Auth::user()->username === $username) {
$u = User::where('username', $username)->first();
$user = new \stdClass();
$user->username = $u->username;
$user->email = $u->email;
$user->address = $u->address;
$user->city = $u->city;
$user->state = $u->state;
$user->zip = $u->zip;
$user->phone = $u->phone;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
$user->location = $u->location;
} else {
$u = User::where('username', $username)->first(['username', 'city', 'state']);
$user = new \stdClass();
$user->username = $u->username;
$user->city = $u->city;
$user->state = $u->state;
$user->follows = $u->follows;
$user->ratings = $u->ratings;
}
Cache::put($key, $user);
if($request->wantsJson()) {
return response()->json($user);
} else {
return view('user/detailed', ['user' => $user]);
}
}
}
I have tried to use something similar to the following in the model calls.
User::where('username', $username)->with('follows', 'ratings', 'location')->find(['username', 'city', 'state');
However when I specify the columns to get from the user table it negates the relation data so it comes back as empty arrays. Is there a different way I can do this which would be cleaner? I despise having to create a stdClass to be a data container in this situation and feel I may be missing something.
// this works
User::where('username', $username)->with('follows', 'ratings', 'location')->first();
// this also works
User::where('username', $username)->first(['username', 'city', 'state']);
// this does not
User::where('username', $username)->with('follows', 'ratings', 'location')->first(['username', 'city', 'state']);
When you specify columns and want to get the related models as well, you need to include id (or whatever foreign key you're using) in the selected columns.
The relationships execute another query like this:
SELECT 'stuff' FROM 'table' WHERE 'foreign_key' = ($parentsId)
So it needs to know the id of the parent (original model). Same logic applies to all relationships in a bit different forms.

Attach user id to a post (Laravel 5.3)

in my app I want to attach a logged in user id to a post, below is my controller :
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input);
$journal->user_id = Auth::id();
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
I tried the above controller it gave error : SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert intojournal(title,abstract,file,id_edition,journalslug,updated_at,created_at) values (Rancang bangun website Jurnal Online jurusan Teknik Informatika Universitas Palangkaraya, ddd, test3.pdf, 1, rancang-bangun-website-jurnal-online-jurusan-teknik-informatika-universitas-palangkaraya, 2016-11-15 03:43:34, 2016-11-15 03:43:34))
I don't understand what I did wrong, if someone can help that would be great. Thanks.
You're trying to create a Journal without specifying the user_id when it's created.
I'd suggest the following:
public function storejournal(JournalRequest $request) {
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$id = $request->id;
$journal = Edition::findOrFail($id)->journal()->create($input + ['user_id' => Auth::id()]);
$journal->user()->attach($request->input('penulis'));
return redirect()->route('edition', ['id' => $id]);
}
Also, don't forget to have user_id set as mass assignable in the Journal class.
The error says you should pass user_id too. You can do this with adding user ID to an $input:
$input = $request->all();
$input['user_id'] = auth()->user()->id;

Laravel 4 - Eloquent relationship find by username

$picture = User::find(Session::get('user_id'))
->pictures()->where('approved', '=', '1')->first();
How can i modify this code according to username instead of Session::get('user_id')
Thanks.
if the user is logged in, try
$pictures = Auth::user()->pictures()->where('approved', '1')->first();
Update
regarding your comment:
try {
$pictures = User::where('name', $searchname)->firstOrFail()->pictures()->where('approved', '1')->first();
}
catch (Exception $e) {
// stuff to do, if no user is found
}

Resources