laravel prefil form inputs from controller - laravel

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');

Related

Laravel not reaching update method and returns edit view again – route wrong

When I click Save on my edit view, my routing brings back my edit view instead of my index view and my update method is never reached.
I noticed that I reach the update method if I remove “UsersRequest $request” from the method parameters. Not sure why, and if it’s related, but I need $request to do my update (see controller code below):
Routes:
Route::get('/users', 'UsersController#index')->name('users.index');
Route::patch('/users/{id}',
[
'as' => 'users.update',
'uses' => 'UsersController#update'
]);
Route::get('/users/{id}/edit', 'UsersController#edit');
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UsersRequest;
//public function update($id, UsersRequest $request)
public function update($id) //- with $request removed, the index view is displayed
{
$user = \Auth::user();
$user->update($request->all());
return view('users.index');
}
Edit view:
{!! Form::model($user, ['method' => 'PATCH', 'action' => [ 'UsersController#update', 'user' => $user->id ] ]) !!}
{!! Form::submit('Save', ['class'=>'btn primary']) !!}
{!! Form::close() !!}
Network after save button clicked
URL Protocol Method Result
/myapp/public/users/1 HTTP POST 302 Goes for the update route
http://000.000.000.000/myapp/public/users/1/edit HTTP POST 200 Redirects to the edit route??
.env
APP_URL=http://000.000.000.000/myapp/public
You're failing whatever validation is present in your UsersRequest form request. When the validation fails, it redirects you back to where you came from, which is your edit view. Your edit view should be updated to show the validation errors so that your users know what fields need to be fixed.
The reason it works when you remove the UsersRequest $request parameter is that the validation is no longer being performed.

laravel 5.1 : how can i use my route in blade?

I want to link to my route in blade. How can i do this?
<a href="roue" > go first</a>
if you define Route name you can use that in your blade :
define Route Name :
Route::get('/admin/transfer/forms-list', [
'as' => 'transfer.formsList',
'uses' => 'Website\TransferController#IndexTransferForms'
]);
now you can use that in your blade like this :
<a href="{{URL::route('transfer.formsList')}}" type="submit">
go first</a>
Of course if you use form collective you can use this :
{!! link_to_route('route.name', 'go first') !!}
There are few ways to use routes in a view.
The simplest one is using route() helper:
go first
If you're using Laravel Collective HTML & Forms, it will create full link, not only path to the route:
{!! link_to_route('route.name', 'go first') !!}
Or:
{!! HTML::linkRoute('mainpage', 'hey') !!}
Using URL facade. Wouldn't recommend, because you're getting redundant code:
go first

Repopulating user inputs after successful validation

I am trying to create a search form where the user has to select from some dropdown menus and enter text in one of a few fields. The problem is I am redisplaying the search page with results below it. To do this I am not redirecting, I am just returning a view with the datasets I need compacted along with it.
Is there any way to get to retrieve input similar to how you would do this Input::old('x') when you were redirecting after failed validation?
The routes are:
Route::get('search', ['as' => 'main.search.get', 'uses' => 'MainController#showSearchPage']);
Route::post('search', ['as' => 'main.search.post', 'uses' => 'MainController#showSearchResults']);
Example of code I have in the view:
{!! Form::open(array('route' => 'main.search.post', 'class' => 'form-inline align-form-center', 'role' => 'form')) !!}
<div class="form-group">
{!! Form::label('product_code', 'Product Code: ',['class' => 'control-label label-top']) !!}
{!! Form::text('product_code', Input::old('product_code'), ['class' => 'form-control input-sm']) !!}
</div>
So when you submit a search, it calls showSearchResults which then returns a view if it succeeds, if it fails validation via my SearchRequest class it gets redirected to the main.search.get route, errors are printed and input is returned to the fields.
I have done a lot of searching and have come up more or less empty handed, it would be nice if there was a way to say ->withInput() when returning a view (not redirecting) or something.
Currently my only solution is to Input::flash() but since I am not redirecting that data persists for an extra refresh. That isn't a terribly big deal at this point, but I was wondering if anyone else had a better solution.
Edit - Code below from controller where view is returned:
...
Input::flash();
return view('main.search', compact('results', 'platformList', 'versionList', 'customerList', 'currencyList', 'customer', 'currency'));
}
Thank you
I had the same problem. The solution that worked for me was to add the following line into the controller.
session(['_old_input' => $request->input()]);
Now I'll explain how it works.
In the view, the global function old() is called:
<input type="username" id="username" class="form-control" name="username" value="{{ old('username') }}" placeholder="Username" autofocus>
This function is in vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
function old($key = null, $default = null)
{
return app('request')->old($key, $default);
}
This calls Illuminate\Http\Request->old():
public function old($key = null, $default = null)
{
return $this->session()->getOldInput($key, $default);
}
Which calls Illuminate\Session\Store->getOldInput():
public function getOldInput($key = null, $default = null)
{
$input = $this->get('_old_input', []);
return Arr::get($input, $key, $default);
}
This call is looking for _old_input in the session. So the solution is to add the input to the session using this value.
Hope this helps.
You can use request instead of old since its the post request
change {{old('product_code')}} to {{request('product_code')}}

Laravel Filtering data between dates

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();

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();

Resources