Unable to Pass Variable from Controller to Drop Down - laravel

I'm trying to get data from a table called solutions and view the solution names in a dropdown list on a form called products.
I've created a provider called DynamicDropdown in App/Providers.
<?php
namespace App\Providers;
use App\Dropdown;
use Illuminate\Support\ServiceProvider;
class DynamicDropdown extends ServiceProvider
{
public function boot()
{
view()->composer('*', function ($view) {
$view->with('product_array', Dropdown::all());
});
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Providers\DynamicDropdown;
use App\Product;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function index(Request $request)
{
$select = [];
foreach ($view as $data) {
$select [$data->id] = $data->solutionname;
}
return view('products.products', compact('select'));
}
}
I've called the select variable in the view but unfortunately, I'm getting an undefined variable error.
Blade
<div class="form-group <?php echo e($errors->has('solution') ? 'has-error' : ''); ?>">
<?php echo Form::label('solution', 'Solution', ['class' => 'control-label']); ?>
<?php echo Form::select('solution', $select, null,
('' == 'required') ? ['class' => 'form-control', 'required' => 'required'] : ['class' => 'form-control']); ?>
<?php echo $errors->first('solution', '<p class="help-block">:message</p>'); ?>
</div>
Error Message is...
ErrorException thrown with message "Undefined variable: select (View:
E:\Laravel\IBMint\resources\views\products\products\form.blade.php)
I tried many ways to fix it. But still could not find a solution. Appreciate if someone could assist.
Thank You.

It is because you are actually calling the $select variable on the wrong form. You return a view
return view('products.products', compact('select'));
which means get the view products.blade.php on the folder products under the view folder.
and based on the error you put the $select variable on the form.blade.php.
Fix will be you return the view form.blade.php like this.
return view('products.products.form', compact('select'));

Related

Trying to get property 'image' of non-object in Laravel

I am working on a laravel project. In this project, when i try to view and edit the profile page. I am getting this error.
ErrorException
Trying to get property 'image' of non-object (View: C:\xampp\htdocs\HomeServices\resources\views\livewire\sprovider\sprovider-profile-component.blade.php)
http://127.0.0.1:8000/sprovider/profile
SproviderProfileComponent.php :-
<?php
namespace App\Http\Livewire\Sprovider;
use App\Models\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class SproviderProfileComponent extends Component
{
public function render()
{
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->first();
return view('livewire.sprovider.sprovider-profile-component',['sprovider'=>$sprovider])->layout('layouts.base');
}
}
Models/ServiceProvider.php :-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ServiceProvider extends Model
{
use HasFactory;
protected $fillable = ['user_id'];
public function category()
{
return $this->belongsTo(ServiceCategory::class,'service_category_id');
}
}
sprovider-profile-component.blade.php
<div class="panel-body">
<div class="row">
<div class="col-md-4">
#if($sprovider->image)
<img src="{{asset('images/sproviders')}}/{{$sprovider->image}}" width="100%" />
#else
<img src="{{asset('images/sproviders/default.jpg')}}" width="100%" />
#endif
</div>
<div class="col-md-8">
<h3>Name: {{Auth::user()->name}}</h3>
<p>{{$sprovider->about}}</p>
<p><b>Email: </b>{{Auth::user()->email}}</p>
<p><b>Phone: </b>{{Auth::user()->phone}}</p>
<p><b>City: </b>{{$sprovider->city}}</p>
<p><b>Service Category: </b>
#if($sprovider->service_category_id)
{{$sprovider->category->name}}
#endif
</p>
<p><b>Service Locations: {{$sprovider->service_locations}}</b></p>
Edit Profile
</div>
</div>
</div>
The only reason this could happen is because $sprovider is null.
When it happens, $sprovider->image will translate to (null)->image, which is indeed Trying to get property 'image' of non-object.
You could do this to prevent $sprovider from being null:
$sprovider = ServiceProvider::where('user_id',Auth::user()->id)->firstOrFail();
By using firstOrFail instead of first, you ensure $sprovider will never be null (like the name suggests, if it doesn't find any provider, it will fail).
You will have another error saying that no provider could be found, this is another issue, probably because you don't have any provider for this user or something like that.
Two possibilities
$sprovider is null and
image key is not available in $sprovider ($sprovider->image) may be you mis-spelled image in database table so for that just use dd($sprovider); or print_r($sprovider); and check image key is available or not.

Validation message not showing below the field in cakephp 3 latest version

I am trying to validate a multiple select field that have jquery chosen applied.
Validation is working perfectly but only problem is that validation message is not showing below the input field.
Here is my files.
profile_edit.ctp
<?php echo $this->Form->create($user,['action' => '', 'role'=>"form",'novalidate'=>true,'method'=>'post','id'=>'ProfileForm','templates'=>['label'=>false,'inputContainer'=>'{{content}}']]); ?>
<?php echo $this->Form->control('user_grades[].grade_id',['multiple','hiddenField'=>false, 'escape'=>false, 'type'=>'select', 'id'=>'sp_grade', 'options'=>App\Model\Table\GradesTable::getGrades('list'),'class'=>'form-control chosen-select']); ?>
<button type="submit" class="btn footer_btns float-left">Save</button>
<?php echo $this->Form->end(); ?>
MyAccountController.php
<?php
public function profileEdit(){
$user = $this->Users->get($this->Auth->user('id'), ['contain'=>['UserGrades']]);
if($this->request->is(['put','post'])){
$data = $this->request->getData();
if(isset($data['user_grades']) && !empty($data['user_grades'])) {
$this->UserGrades->deleteAll(['user_id' => $this->Auth->user('id')]);
}
if(null == $this->request->getData('user_grades')){
$this->request = $this->request->withData('user_grades.0.grade_id','');
}
$user = $this->Users->patchEntity($user, $this->request->getData(), [
'validate' => 'editProfileSection',
'associated' => [
'UserGrades' => ['validate'=> 'editProfileSection']
]
]);
if(empty($user->getErrors())){
if ($this->Users->save($user)) {
$this->Flash->success(__('Succesfully updated <strong>'.$user->full_name .'</strong> Information||Success'));
return $this->redirect(['action' => '']);
}
}
$this->Flash->error(__('Please check your inputs and try again.||Action Failed!'));
}
$this->set(compact('user'));
}
UserGradesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
use Cake\ORM\RulesChecker;
use Cake\Validation\Validator;
class UserGradesTable extends Table {
public function initialize(array $config) {
$this->addBehavior('Timestamp');
$this->addBehavior('Trim');
}
public function validationEditProfileSection(Validator $validator) {
$validator
->notEmpty('grade_id',"Please select at least one grade.");
return $validator;
}
}
I have tried to get error message and got following:
Array
(
[user_grades] => Array
(
[0] => Array
(
[grade_id] => Array
(
[_empty] => Please select at least one grade.
)
)
)
)
But this error is not showing below the input field. Any help will be appreciated.
You are not using the correct naming scheme for the form control, you cannot use [], if you want the form helper magic to work, then you must supply the actual index, ie:
user_grades.0.grade_id
See also Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

Edit & Update In Codeigniter

While doing update i am getting following error
Severity: Notice Message: Undefined variable: user
This is my controller:
public function update_user_id($user_id) {
if($this->input->post('submit')){
$courses = array(
'user_name'=>$this->input->post('user_name'),
'email'=>$this->input->post('email')
);
$this->users_model->update_user($user_id,$users);
$base_url=base_url();
redirect("$base_url"."Dashboard/update_user_id/$user_id");
}
$result['user']=$this->users_model->user_id($user_id);
$this->load->view('edit_user',$result);
}
Which is my view
<?php echo form_open(base_url().'Admin/update_user_id/'.$user[0]->user_id);?>
User Name: <input type="text" name="user_name" value=" <?php echo $user[0]->user_name; ?>">
Email: <input type="text" name="email" value=" <?php echo $user[0]->user_name; ?>">
<?php echo form_close();?>
Don't know whats wrong with the code
Always follow documentation. By CI council convention, your class names should follow file names. I suppose you have that right. But you didn't follow demand for ucfirst() file and class names.
So in your case file shouldn't be named CoursesModel neither class should be named CoursesModel, but you should name your file and class Coursesmodel. Remember ucfirst() rule (regarding CI3+) for naming all classes wether controllers, models or libraries.
Also, if you load those files (models and libraries), for libraries always use strtolower() name while for models you can use both strtolower() and ucfirst() formatted name.
Personaly, I use to load libraries with strtolower while using to load models with ucfirst name and that way I make difference between those just having a quick look on code.
Try with:
Courses_m.php (This way I speed up parsing a little bit)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_m extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function update_course($course_id, $courses)
{
// your DB task --should return something
return true ?: false;
}
}
And in controller:
Courses_c.php (in APPPATH . 'config/routes.php' you can set what ever name you like for your route)
<?php defined('BASEPATH') or exit('Not your cup of tea.');
class Courses_c extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->library('form_validation');//just an library loading example
$this->load->model('Courses_m');//notice first capital here
}
public function update_course_id($course_id)
{
if($this->input->post('submit'))
{
$courses = array(
'course_name'=>$this->input->post('course_name'),
'no_of_hours'=>$this->input->post('no_of_hours')
);
// pay attention on capital first when you calling a model method
// need to be the same as in constructor where file is loaded
$this->Courses_m->update_course($course_id,$courses);
// you can use this way
redirect(base_url("Dashboard/update_course_id/$course_id"));
}
// use else block to avoid unwanted behavior
else
{
$result['course']=$this->Courses_m->course_id($course_id);
$this->load->view('edit_course',$result);
}
}
}

Auth::check() worked in controller but not working in view?

I used Auth::attempt() to log user:
if (Auth::attempt(['email' => $email, 'password' => $password], true)) {
return redirect('/');
}
else{
return 'wrong email or pass';
}
Then I reload browser and call function:
if (Auth::check()) {
return 1;
}
And this return 1;
But when I call:
#if (\Illuminate\Support\Facades\Auth::check())
echo '<label style="width: 20%;color: #ff3f41;margin-left: 10px;">login</label>';
#else
echo '<label style="width: 20%;color: #ff3f41;margin-left: 10px;">nothing</label>';
#endif
This print nothing.
Any helps. Thanks.
instead of
#if (\Illuminate\Support\Facades\Auth::check()) ...
try to use
#if(Auth::Check())
This should work. you dont need to call method by its full path in Blade template
#if(Auth::Check())
<label style="width: 20%;color: #ff3f41;margin-left: 10px;">login</label>
#else
<label style="width: 20%;color: #ff3f41;margin-left: 10px;">nothing</label>
#endif
No need namespace in view Because it is defined in Facades, Check it in config/app.php
And if you use brackets and echo in blade You need to wrap them in <?php tag //code echo 'something' ?>
Laravel way!
If you need to echo something in View use {{ }} or {!! !!} The difference {{ }} escape HTML tags, {!! !!} doesn't escape HTML
goto App/Providers/AppServiceProvider.php in boot(){ } section write this line view()->share('key', 'my name is Rome');
using this you will be able to globally access "key" variable value in all off your templates
eg: see below
<?php
namespace App\Providers;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
view()->share('key', 'my name is Rome');
}
}

Stumped by CodeIgniter controllers found but not found

OK, I admit it. I'm a CI newbie. I'm doing something really basic wrong and I've been at it for a couple of hours and can't find my error.
I have a controller called login. It's in the resources folder in my controllers folder. It loads a view called login_form. But for the life of me it will not load if I go to domain.com/resources/login or domain.com/resources/index. But I can get to it via a route:
$route['engineering-resources/login'] = "resources/login";
Even when I get to it this way, my form action isn't found. Here is my form:
<?php
echo form_open('resources/login/validate_credentials'); //folder/controller/method. I think this is where my problem is
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
The path is my resources folder in my controllers folder, and the controller is the login controller using the validate_credentials method. Here is the pertinent part of my login controller:
class Login extends Controller {
function index()
{
$data['title'] = 'Engineering Resources | Login';
$data['main_content'] = 'resources/login_form';
$this->load->view('templates/main.php', $data);
}
function validate_credentials()
{
$this->load->model('login/membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('resources/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
The index function works when I use the route, but not when I use the above domain.com paths. I assume that is why it cannot find the validate_credentials method. What am I doing wrong?
Here is main.php
<?php $this->load->view('includes/header.php'); ?>
<?php $this->load->view('includes/nav.php'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer.php'); ?>
$route['engineering-resources/login'] = "resources/login";
This does not route to engineering-resources/login/validate_credentials to resources/login/validate_credentials
You should have something like this:
// not tested
$route['engineering-resources/login/(\S*)'] = "resources/login/$1";
One more thing is that if you are using routes, you should use the routes from your views too..
echo form_open('engineering-resources/login/validate_credentials');

Resources