Laravel Filtering data between dates - laravel

I'm beginner in Laravel and web development and I have a silly question, I'm building a system that lists the user financial transactions. In the homepage is listed all the transactions made by the user. I put two fields up there to make the date filter of the transactions, but I don't know how to proceed this filter in Laravel.
I'm using datepicker and it is working fine, I also know that the validation system allows me to use Laravel date: after and date: before, but I don't know how and in which method in the controller send these dates. Here's my dates form code:
{!! Form::open(['route' => 'transactions.index']) !!}
{!! Form::label('data_inicio', 'De: ') !!}
{!! Form::input('date', 'data_inicio', null, ['class' => 'datepicker', 'data-date-format' => 'dd/mm/yy']) !!}
{!! Form::label('data_fim', 'Até: ') !!}
{!! Form::input('date', 'data_fim', null, ['class' => 'datepicker', 'data-date-format' => 'dd/mm/yy']) !!}
{!! Form::submit('Enviar') !!}
{!! Form::close() !!}
The method in the controller which calls the view of the homepage is the index, here's the index code:
public function index()
{
$transactions = Auth::user()->transactions;
return view('transactions.index', ['transactions' => $transactions]);
}
Here is how I show the data in the view:
#foreach( $transactions as $transaction )
<tr>
<td>{!! date('d-m-Y', strtotime($transaction->created_at)) !!}</td>
<td>{!! $transaction->title !!}</td>
<td>{!! $transaction->amount !!}</td>
</tr>
#endforeach
I need to send these dates I got to this same method (index) when the Pesquisar button was clicked to be able to seek in the database only the transactions of the proposed date, the problem is I do not know do this.
I tried to send these dates as parameter request to the index method, modifying it like this:
public function index(Request $request)
I got a Column Not Found error when I click in the submit, but I'm not using this request in any query in the method.
I really think that it has a simple way to do it and I appreciate any help!!
Here's my model class:
class Transaction extends Model {
protected $table = 'transactions';
protected $guarded = [];
public function users()
{
return $this->belongsTo('App\User');
}
}

Try this to obtain the dates in your controller:
$data_inicio = Input::get('data_inicio');
$data_fim = Input::get('data_fim');
Then you can use the dates to query your Transaction relation (assuming this a one to many relationship and is configured propperly)
$transactions = Transaction::whereBetween('created_at',[$data_inicio, $data_fim])->where('user_id',Auth::id())->get();

Related

laravel prefil form inputs from controller

Hi I'm using laravel forms.
{!! Form::text('product_name', null, array('class' => 'form-control date_pick')) !!}
Is there a way to set this default input from controller?. Think we can do it with Flash but I couldn't find an example. I want to take vlues from a model and prepopulate.
$products = Products::all();
It would be great if someone know how to do this. What is the easiest way to do it?
This is done with a basic edit route where you simply use:
In ModelController you would call the edit page:
public function edit(ModelName $model) {
return view('name.of.the.blade.view', compact('model')); // if using compact then without dollar symbol
}
In blade view simply make the form with all the input fields you have for that model:
{!! Form::model($model, ['method' => 'PATCH', 'route' => ['model.update', $model->id],]) !!}
Now all the form fields will have the values from that model.
{!! Form::close() !!}
And the edit and update route (inside routes/web.php) would be like this:
Route::get('/model/{model}/edit', 'ModelController#edit')->name('model.edit');
Route::patch('/model/{model}', 'ModelController#update')->name('model.update');

Laravel send email to address from database

In my index view I show all the users and there is a button that will change the user status to active and not active. The code looks like this:
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->surname}}</td>
<td>{{$user->email}}</td>
<td>
#if($user->is_active == 0)
{!! Form::model($user, ['method' => 'PUT', 'action'=>['AdminUserController#activateuser', $user->id]]) !!}
{!! Form::submit('Activate', ['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}
#else
{!! Form::model($user, ['method' => 'PUT', 'action'=>['AdminUserController#activateuser', $user->id]]) !!}
{!! Form::submit('De-Activate', ['class'=>'btn btn-danger']) !!}
{!! Form::close() !!}
#endif
</td>
<td>{{$user->cell}}</td>
<td><button class="btn btn-primary">View Property</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>
#endforeach
So when I click on activate/deactivate button I trigger my activateuser function of the controller. After activation, an email is sent.
The controller looks like this:
public function activateuser(Request $request, $id){
$user = User::findOrFail($id);
if($user->is_active == 0){
$user->update([$user->is_active = 1]);
Mail::send(new activateUser());
}
else{
$user->update([$user->is_active = 0]);
}
return redirect()->back();
}
At the moment the email is going to myself and my Mailabçe looks like this:
public function build()
{
return $this->view('emails.activateuser')->to('wosleybago#gmail.com');
}
What I want instead is to send the email to the email address from the user email in the database table.
How can I do that?
So, someho I should get the $user->email
I usually want my emails have all the information in itself, so I pass User instance or whatever instance that holds data required to compose the mail.
So the Mailable has __construct(..) like this:
/**
* #var \App\User
*/
public $user; // since this is a public property its going to be available in view of mailable as $user
__construct(App\User $user) {
$this->user = $user;
// further more I set the to(), this is what you are after
$this->to($user->email, $user->name);
// and subject
$this->subject('You are activated!');
}
...
And now all you need to do in the controller is the following:
Mail::send(new activateUser($user));
As mentioned above, $user is available in the mail-view so you can use it there as well:
Hi, {{ $user->name }},
...
Note: change the activateUser to ActivateUser to follow PSR-2
Class names MUST be declared in StudlyCaps.
I also use queued mails so I set the $timeout and $tries properties right on the Mailable class.
Sending email is described in Doc: https://laravel.com/docs/5.6/mail#sending-mail
Put this code inside activateUser() function
Mail::to($user)->send(new YourMailableName());
Do not forget to import Mail and YourMailableName using "use" keyword.
Or you can use user email instead object
Mail::to($user->email)->send(new YourMailableName());
And remove ->to('wosleybago#gmail.com') from your Mailable/
You should pass User Email in when creating new activateUser instance, like so
Mail::send(new activateUser($user->email));
And then use this attribute later.
Sending Email to particular a person is quite simple. My suggestion would be as follows:
Use Queue to send mail later as it will take some time to respond from controller to view.
In existing code you can get the email of the current user and send it using a helper to() that comes with mail functionality of laravel.
You can code it like this.
if($user->is_active == 0){
$user->update([$user->is_active = 1]);
Mail::to($user->email)->send(new MailableClassInstance);
}

How to use a Form::Select with a Pivot Table in Laravel 5.6

I try to use Form::select in Laravel 5.6, but when I went to the Edit Page, in the select, there are options with all the data of the object Model instead of a regular field.
I have a Game Model with a relationship ManyToMany with a Tag Model.
In my edit function from the Game Controller
public function edit($item)
{
$tags = Tag::all();
return view('megadmin.games.edit', compact('item', 'tags'));
}
In my Form Blade :
{!! Form::select('tags', $tags, array_pluck($tags, 'id_tag','name'), ['class' => 'form-control'])!!}
Here the result :
The result
I just want a normal select/options with the data AND i want to retrieve the model Tag associated with the Game in the Game Form.
Thanks you for your help ^^
I assume you are using Form model binding, so you can do this:
In your Game model create a new method only for you Form Model Binding:
class Game extends Model
{
use FormAccessible;
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function formTagsAttribute()
{
return $this->tags()->pluck('id_tag');
}
}
In your Controller:
public function edit($item)
{
$tags = Tag::pluck('name', 'id_tag');
return view('megadmin.games.edit', compact('item', 'tags'));
}
In your view:
{!! Form::model($game, [$attributes]) !!}
{!! Form::select('tags', $tags, null, ['class' => 'form-control']) !!}
.
.
.
{!! Form::close() !!}
Controller
public function edit($item)
{
$tags = Tag::all();
$goodTag = $item->tags()->first()->id;
//here assuming `$item` is your Game object and
//you have ManyToMany relation with tags with `tags` function in game model
//lots of assuming
return view('megadmin.games.edit', compact('item', 'tags', 'goodTag));
}
View
{!! Form::select('tags', array_pluck($tags,'name', 'id_tag'), $goodTag, ['class' => 'form-control'])!!}
Here is the laravel form select source code https://github.com/illuminate/html/blob/master/FormBuilder.php#L393
and array_pluck https://laravel.com/docs/5.6/helpers#method-array-pluck

Laravel 5 Relationship Not Working?

In my app I have few models: User and Profile. The User model is only for companies, my app is for companies only. When a user registers, they only fill in their name, email address and password. My Profile model has columns for company name, address etc. My profile form does not work; not saving to the database. Here is the setup:
Controller for the form:
public function update($company_name)
{
$user = User::whereCompanyName($company_name)->firstOrFail();
$user->fill(Input::all());
$user->save();
flash('You have successfully edited your profile');
return redirect('/');
}
User.php:
public function profile()
{
return $this->hasOne('Profile');
}
Profile.php:
protected $fillable = ['company_name', 'company_logo', 'company_founded'];
public function user()
{
return $this->belongsTo('App\User', 'user_id','ID');
}
The Form:
{!! Form::model($user, array('method' => 'PATCH', 'route' => array('profile.update', $user->company_name), 'files' => true)) !!}
{!! Form::hidden('user_id', Auth::user()->id) !!}
// more fields
<div class="form-group">
{!! Form::label('company_name', 'Company Name') !!}
{!! Form::text('company_name', null, ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Update Profile', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Have I set the relationship correct? Nothing is saving to the database.
You’re updating the user model and the user model only. You need to also set the attributes in the profile relation:
$user->update(Input::all());
$user->profile->update(Input::all());
Your controller action could also be tidied up a bit, by using route–model binding to inject your User model instance, and also use the service container to provide a Request instance too so you’re not using the Input façade:
public function update(User $user, Request $request)
{
$user->update($request->all());
$user->profile->update($request->all());
flash('You have successfully updated your profile.');
return redirect('/');
}
I want to comment but do not have enough reputation :( A few days ago I found a little problem with this approach:
$user->update(Input::all());
$user->profile->update(Input::all());
In this case the mutators in related model (profile in the example) like this are not invoked (may be a bug):
public function setLoremIpsumAttribute($attr)
{
# code
}
In controller I tried another approach and it worked:
$user->update($request->all());
$user->profile->fill($request->all()['profile'])->push();
In Laravel 5 when you want to chain with relation, you need for exemple (Post with comment related) use the method from your comment.
Post::find(id)->comment()->where(your where statement)
Docs from Laravel:
If you need to add further constraints to which comments are retrieved, you may call the comments method and continue chaining conditions:
$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

Creating a Value List Using Values from Another Table in Laravel

I have a simple database application that records contacts (name, address, etc.). I am trying to draw on various other tables to generate value lists for the forms. Then I would like to have all form values entered by the user to be saved into the appropriate tables on submit.
For example, I have the people table which includes the name and address. I have a title table with the different possible values for the title (i.e. Mr., Mrs., Ms. Dr.). Upon filling in the contact form, I would like to generate the values for the title field in the form from the title table. I am trying to do this one model for Contact that includes separate classes for the people table and the title table.
In my ContactController.php I have:
class ContactController extends Controller {
public function index()
{
$people = Contact::all();
// return main homepage for Contacts section
return view('pages.contacts.home', compact('people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$title = Contact::lists('title', 'id');
return view('pages.contacts.create');
}
In my Contact.php model I have the following:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model {
protected $table = 'people';
protected $fillable = [
'title_id',
'name_first',
'name_middle',
'name_last',
'date_birth',
'date_death',
'bio',
'created_at',
'modified_at'
];
public function title() {
return $this->belongsTo('Title', 'title_id', 'id');
}
}
class Title extends Model {
protected $table = 'title';
protected $fillable = [
'title',
'created_at',
'modified_at'
];
public function contacts() {
return $this->hasMany('Contact', 'title_id', 'id');
}
}
In the form I have the following:
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::select('title', $title) !!}
</div>
<div class="form-group">
{!! Form::label('name_first', 'First Name: ') !!}
{!! Form::text('name_first', null, ['class' => 'form-control']) !!}
{!! Form::label('name_middle', 'Middle Name: ') !!}
{!! Form::text('name_middle', null, ['class' => 'form-control']) !!}
{!! Form::label('name_last', 'Last Name: ') !!}
{!! Form::text('name_last', null, ['class' => 'form-control']) !!}
{!! Form::label('name_nick', 'Nickname: ') !!}
{!! Form::text('name_nick', null, ['class' => 'form-control']) !!}
</div>
I am getting an error saying the variable title is undefined. I cannot determine why the value list is not being returned. Are my relationships returned incorrectly?
You don't pass the $title variable to your view.
In your create method in the ContactController, assign the $title variable to your view:
public function create()
{
$title = Contact::lists('title', 'id');
return view('pages.contacts.create')->with('title', $title);
}
See http://laravel.com/docs/5.0/views for more documentation.

Resources