Define default values for Laravel form fields - php

To pre-populate form field, we can add 'value' to form field in create.blade.php:
{{ Form::text('title', 'Some default title') }}
Is there a way to do that task elsewhere (maybe in model or controller?). I'd like to have code for form fields identical in create & edit view. Thanks!

Okay, so here we are... I used Laravel's form model binding in the example. (I work with User model/db table).
If this topic is not clear for you, take a look at this http://laravel.com/docs/html#form-model-binding
// Controller
class UsersController extends BaseController
{
...
// Method to show 'create' form & initialize 'blank' user's object
public function create()
{
$user = new User;
return View::make('users.form', compact('user'));
}
// This method should store data sent form form (for new user)
public function store()
{
print_r(Input::all());
}
// Retrieve user's data from DB by given ID & show 'edit' form
public function edit($id)
{
$user = User::find($id);
return View::make('users.form', compact('user'));
}
// Here you should process form data for user that exists already.
// Modify/convert some input data maybe, save it then...
public function update($id)
{
$user = User::find($id);
print_r($user->toArray());
}
...
}
And here come the view file served by controller.
// The view file - self describing I think
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
#if(!$user->id)
{{ Form::model($user, ['route' => 'admin.users.store']) }}
#else
{{ Form::model($user, ['route' => ['admin.users.update', $user->id], 'method' => 'put']) }}
#endif
{{ Form::text('firstName') }}
{{ Form::text('lastName') }}
{{ Form::submit() }}
{{ Form::close() }}
</body>
</html>

Yes, let's consider the following example:
View:
{{ Form::text('title', $title) }}
Controller:
$title = 'Some default title';
if($article) {
$title = $article->title;
}
return View::make('user.login')->with('title', $title)
Then you will have a text-input with either Some default title or the title from $article, if $article isn't equal to false

All you need to do is include a conditional in your blade template.
Lets assume your database table has a field myfield, which you want to default to mydefault.
Just include the following in a partial view which is called by the create and edit views:
#if(isset($myfield))
{{ Form::input('text','myfield') }}
#else
{{ Form::input('text','myfield','mydefault') }}
#endif
You don't have to anything else.

if you mean placeholder you can do this
{{ Form::password('password', array('placeholder' => 'password'))}}

Probably easier (Laravel 5):
{{ Form::text('title', isset($yourModel) ? null : 'Some default title') }}
That is to assume you are using the form as a partial. It should populate the value if the model for the form exists (you are editing or patching record) else it should show you the default you wish.

When you are using the Schema builder (in Migrations or somewhere else):
Schema::create(
'posts', function($table) {
$table->string('title', 30)->default('New post');
}
);

If you want to do this conditionally, an alternative method of solving this could be to perform a check instead. If this check passes, set the default (as is done below with $nom as an example). Otherwise, leave it empty by setting it to null explicitly.
{{ Form::text('title', (isset($nom)) ? $nom : null) }}

Related

Laravel: Trying to get property of non-object when taking data via foreign key

I have a User and a Tag model. Both are linked by a 1:N relation.
I am trying to take col tag_name from user model. However I am receiving this error:
Trying to get Trying to get property 'tag_name' of non-object.
User model has
// linking with table tag
public function tags(){
return $this->hasMany('App\Tag');
}
Tag model has
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
My view has
{{ Form::checkbox('tag[]',$user->tag_id,['class'=>'cats']) }}
{{ Form::label('tb',$user->tag_id->tag_name,['class'=>'btn btncategory']) }}
Controller has the following in index function
$user = User::find($user_id);
return view('user.create_post')->with('user', $user );
Route:
Route::get('create', 'PostsController#index');
Please help me where I am wrong.
Thanks in advance.
The problem is that your user has multiple tags you need to loop through each of them:
In blade file:
#foreach ($user->tags as $tag)
<label class="btn btncategory">
<input type="checkbox" name=tag[] value="{{$tag->id}}" class="cats" />
{{$tag->name}}
</label>
#endforeach
Now when you submit this you should have all checked tags in the array request()->input('tag')
Note I've removed the Form:: because I like to put the checkboxes inside the label but you can just use the Form:: style if you want like below:
#foreach ($user->tags as $tag)
{{ Form::checkbox('tag[]',$tag->id,['class' => 'cats']) }}
{{ Form::label('tb',$tag->name,['class' => 'btn btncategory']) }}
#endforeach

Laravel loading page from DB trans function not working

I'm storing pages dynamically in my database (pages table).
When I store blade function like {{ trans('langfile.key') }} in my database and then present it in my view, blades {{}} functions are not triggered. Any ides on how to accomplish this?
Table row
1 test This is our test title {{ trans('commons.mobile') }} 2016-10-06 08:37:49 2016-10-06 08:42:48
Controller
public function show(Request $request, $slug){
$page= DB::table('pages')->where('slug', $slug)->first();
return View::make('page')->with('page', $page->page_content);
}
View
#extends('layouts.app')
#section('content')
<div class="container contentpadding"></div>
{!! $page !!}
#stop
Result is {{ trans('commons.mobile') }} and not Mobile (if lang = us)

Laravel: print URL or default value in blade view

I have Post model which has user function returning User model - creator of the post.
class Post extends Model
{
/**
* Get the user that owns the post.
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
In blade view I achieved how to print author name
{{ $post->user->name or 'Anonymous' }}
Above code works, but it is very hmm sensitive?
For example, I tried change this code to:
{{ $post->user->name, 'Anonymous' }}
<?php $post->user->name or 'Anonymous' ?>
Results? Trying to get property of non-object error on line with this code.
Maybe I am skipping something simple but important. How to print URL or default value in blade view. Pseudo code what I mean:
{{ '' or 'Anonymous' }}
Try
{{ isset($post->user->name) ? '' : 'Anonymous' }}
If this doesn't work (I haven't check it) try something like this:
#if (isset($post->user->name))
#else
Anonymous
#endif
Actually the error is not because the code is sensitive, it is because you are actually trying to access non objects values.
To achieve what you are looking for:
{{ isset($post->user)?'' : 'Anonymous' }}

laravel how to get single row and post to view

in MySql database i have systemSetting table and this have any data.
in this table i have this fields :
id - site_copyright - date
i want to fill form with this single row.
{{ Form::model($siteSettings) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::label('site_copyright' , 'copy right') }}
{{ Form::text('site_copyright', null , array('id'=>'site_copyright' )) }}
{{ Form::close() }}
UPDATE:
in CONTROLLER of that i have this:
public function getIndex()
{
$siteSettings = SystemSetting::all();
return View::make('back_end.layouts.manageHeaders')->with('siteSettings', $siteSettings);
}
in Result, form could not parse data to input fields.
i get error for this :
$siteSettings->site_copyright
This is a duplicate of many questions, such as this: Laravel display table record using query
The short answer is: use first() method to get a single entry.
You're using form model binding, so change your controller to:
public function getIndex()
{
$siteSettings = new SystemSetting;
return View::make('back_end.layouts.manageHeaders', compact('siteSettings'));
}
Query work on 5.1 or more
return DB::table('users')->where('id', $id)->value('field_name');
//if lower version of laravel like 4.2
DB::table('users')->where('id', $id)->pluck('field_name');

Can't get a simple Laravel Login controller setup to work

I am just starting with Laravel after finally deciding to move from CodeIgniter, however I cannot get a simple login form to work. I keep getting that "MethodNotAllowedHttpException" error.
Here is how my Controller looks
class LoginController extends BaseController {
public function login()
{
$username = $_POST['username'];
$password = $_POST['password'];
Login::login($username, $password);
// ^ Call to Login model to check the user's credentials - everything fine there
}
}
Here is my view
{{ Form::open(array('url' => 'LoginController/login')) }}
{{ Form::text('username') }}
{{ Form::password('password') }}
{{ Form::submit('Submit') }}
{{ Form::close }}
And my route for this is like
Route::get('LoginController/login', 'LoginController#login');
I'm doing something horribly wrong somewhere, can you guys please point it out?
Thanks!
Seems like you are just routing the GET method. You should also route the POST method to make your controller work:
Route::get('LoginController/login', 'LoginController#login');
Route::post('LoginController/login', 'LoginController#login');
Normally, It is better to have to separate methods in your controller to handle different logic. Something as follow:
Route::get('login', 'LoginController#showLogin');
Route::post('login', 'LoginController#processLogin');
That way you will have your controller's methods more specific, one that just show the login page, and the other that actually do the login process.
Update
If you want to retrieve input values within Laravel, you should use the Input class, so you will replace your current code:
$username = $_POST['username'];
$password = $_POST['password'];
to be as follow:
$username = Input::get('username');
$password = Input::get('password');
Happy coding!
You need to specify a form method as POST so that it reads
{{ Form::open(array('url' => 'LoginController/login', 'method'=>'POST')) }}
{{ Form::text('username') }}
{{ Form::password('password') }}
{{ Form::submit('Submit') }}
{{ Form::close }}
And the in your routes file add the following
Route::post('/login', array('uses' => 'LoginController#login')

Categories