How do I update user profile? Laravel-5 - php

Just want to start by saying I have no clue what I'm doing...
I have a user_info table that looks like this
Schema::create('user_info', function(Blueprint $table){
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('address');
$table->string('city');
$table->string('state');
$table->string('zip');
$table->text('description');
$table->text('experience');
$table->timestamps();
});
I'm having trouble creating the update controller which looks like this right now.
public function update(Request $request)
{
$user = $request->user();
$data['description'] = $request->input('description');
$data['experience']=$request->input('experience');
$user->user_info -> $data->save();
}
again...no clue what I'm doing...
and this be my form:
<div class='col-md-10 well form-well'>
{!! Form::open(['method' => 'PATCH', 'action'=> ['UserController#update', Request::user()->id]]) !!}
<div class='row'>
<div class='form-group'>
<div class='col-md-2'>
{!! Form::label('description', 'About You')!!}
</div>
<div class='col-md-7'>
{!! Form::textarea('description', null, ['class'=>'form-control', 'rows'=>'3'])!!}
</div>
</div>
</div>
<div class='row'>
<div class='form-group'>
<div class='col-md-2'>
{!! Form::label('experience', 'Experience and Skills')!!}
</div>
<div class='col-md-7'>
{!! Form::text('experience', null, ['class'=>'form-control'])!!}
</div>
</div>
</div>
<div class='form-group'>
{!! Form::submit('Save Changes',['class'=> 'btn btn-md btn-success']) !!}
{!! Form::close()!!}
</div>
Update: I was able to update it like this:
$user->user_info->description = $data['description'];
$user->user_info->experience = $data['experience'];
$user->user_info->save();
But is there a way I can do something like :
$user->user_info->$request::Input::all();
$user->user_info->save();

Try this:
public function update(Request $request, $id)
{
$User = User::with('user_info')->find($id);
if(!$User) {
return response('User not found', 404);
}
$UserInfo = $User->user_info;
if(!$UserInfo) {
$UserInfo = new UserInfo();
$UserInfo->user_id = $id;
$UserInfo->save();
}
try {
$values = Input::only($UserInfo->getFillable());
$UserInfo->update($values);
} catch(Exception $ex) {
return response($ex->getMessage(), 400);
}
}
also in Your UserInfo model add this:
protected $fillable = array('description', 'experience');
public function getFillable() {
return $this->fillable;
}

Related

Undefined Offset: 1 laravel 6

i wanna update the data of categories on multilevel choose item, but i had a problem, i can edit the categories without choose a parent, but i can't edit the categories when i choose a parent. then its showing a error called undefined offset:1 and here the trace error
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
C:\laragon\www\oesingcoffee\vendor\laravel\framework\src\Illuminate\Validation\Concerns\ValidatesAttributes.php:874
this is validates attrib in laravel framework
protected function getExtraConditions(array $segments)
{
$extra = [];
$count = count($segments);
for ($i = 0; $i < $count; $i += 2) {
$extra[$segments[$i]] = $segments[$i + 1]; //this is the 874 line
}
return $extra;
}
this is the CategoryRequest class
class CategoryRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$parentId = (int) $this->get('parent_id');
$id = (int) $this->get('id');
if($this->method() == 'PUT'){
if($parentId > 0){
$name = 'required|unique:categories,name,'.$id.'id,parent_id,'.$parentId;
}else{
$name = 'required|unique:categories,name,'.$id;
}
$slug = 'unique:categories,slug,'.$id;
}else{
$name = 'required|unique:categories,name,NULL,id,parent_id,'.$parentId;
$slug = 'unique:categories,slug';
}
return [
'name' => $name,
'slug' => $slug,
];
}
}
this is my controller to update the data
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->update($params)) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
this the view form
#extends('admin.layout')
#section('content')
#php
$formTitle = !empty($category) ? 'Update' : 'New'
#endphp
<div class="content">
<div class="row">
<div class="col-lg-6">
<div class="card card-default">
<div class="card-header card-header-border-bottom">
<h2>{{ $formTitle }} Category</h2>
</div>
<div class="card-body">
#include('admin.partials.flash', ['$errors' => $errors])
#if (!empty($category))
{!! Form::model($category, ['url' => ['admin/categories', $category->id], 'method' => 'PUT']) !!}
{!! Form::hidden('id') !!}
#else
{!! Form::open(['url' => 'admin/categories']) !!}
#endif
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'form-control', 'placeholder' => 'category name']) !!}
</div>
<div class="form-group">
{!! Form::label('parent_id', 'Parent') !!}
{!! General::selectMultiLevel('parent_id', $categories, ['class' => 'form-control', 'selected' => !empty(old('parent_id')) ? old('parent_id') : !empty($category['parent_id']) ? $category['parent_id'] : '', 'placeholder' => '-- Choose Category --']) !!}
</div>
<div class="form-footer pt-5 border-top">
<button type="submit" class="btn btn-primary btn-default">Save</button>
Back
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endSection
this is the migration
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('slug');
$table->bigInteger('parent_id');
$table->timestamps();
});
}
this is the edit method in controller
public function edit($id)
{
$category = Category::findOrFail($id);
$categories = Category::orderBy('name', 'asc')->get();
$this->data['categories'] = $categories->toArray();
$this->data['category'] = $category;
return view('admin.categories.form', $this->data);
}
you should try save() method.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$params['slug'] = Str::slug($params['name']);
$params['parent_id'] = (int)$params['parent_id'];
$category = Category::findOrFail($id);
if ($category->save()) {
Session::flash('success', 'Category has been updated.');
}
return redirect('admin/categories');
}
Replace with above one.
public function update(CategoryRequest $request, $id)
{
$params = $request->except('_token');
$category = Category::findOrFail($id);
$category->slug = Str::slug($params['name']);
$category->parent_id = (int)$params['parent_id'];
$category->save();
Session::flash('success', 'Category has been updated.');
return redirect('admin/categories');
}
I think your issue is inyour validation rule (specifically in your unique rule). May I suggest something else ?
I don't have the environment to test it right but now, so it may have some tweak to do.
use Illuminate\Validation\Rule;
...
public function rules()
{
$name = [
'required',
Rule::unique('categories')->where(function ($query) {
return $query->where('name', $this->name)
->where('parent_id', $this->parent_id);
})->ignore($this->id, 'id'),
];
$slug = [
Rule::unique('categories', 'slug')->ignore($this->id, 'id'),
];
return [
'name' => $name,
'slug' => $slug,
];
}

Laravel 5.4 How to update profile of applicant guest that is logged in

I am new to laravel and I want to let the user update his/her profile when logged in. I want to get the ID of the user when updating his/her profile but when I click on the edit view to pass the data using the id I got this error:
(1/1) ErrorException
Missing argument 1 for App\Http\Controllers\Applicant\HomeController::edit()
Here is the code to my controller:
public function edit($id)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant');
return redirect(route('applicant.home'));
}
return view('applicant-dashboard.edit')->with('applicants', $applicant);
}
public function update($id, UpdateApplicantRequest $request)
{
$applicant = $this->applicantRepository->findWithoutFail($id);
if (empty($applicant)) {
Flash::error('Applicant not found');
return redirect(route('applicant.index'));
}
$input = $request->all();
$cashier = $this->applicantRepository->update([
'name' => $input['name'],
'email' => $input['email'],
'password' => bcrypt($input['password']),
'address' => $input['address'],
'cellphone_no' => $input['cellphone_no']], $id);
Flash::success('Profile updated successfully.');
return redirect(route('applicant.index'));
}
Here is the code in my routes file:
Route::get('/edit', 'HomeController#edit')->name('applicant.edit');
Here is the code in my blade file:
#extends('layouts.app')
#section('content')
<section class="content-header">
<h1>
Applicant Profile
</h1>
</section>
<div class="content">
{{-- #include('adminlte-templates::common.errors') --}}
<div class="box box-primary">
<div class="box-body">
<div class="row" style="padding-left: 20px">
{!! Form::model($applicant, ['route' => ['applicant.update', $applicant->id], 'method' => 'patch']) !!}
#include('applicant-dashboard.fields')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
You need to pass the id into your route:
Route::get('/edit/{id}', 'HomeController#edit')->name('applicant.edit');
You pass the ID into web.php:
Route::get('edit/{ID}', 'HomeController#edit')->name('applicant.edit');

Laravel unknown column

I have a problem with this error:
https://pastebin.com/cgm5yq0P
This is my form:
https://pastebin.com/bSU5X5EC
This is my web.php (route controller):
Route::post('/komentarz', 'VideosController#postComment');
This is my VideoController postComment function:
https://pastebin.com/SYbEjB8H
This is my Comment model:
https://pastebin.com/SxHX6gTP
This is my User model comments function:
public function comments() {
return $this->hasMany('App\Comment');
}
This is my Video model comments function:
public function comments(){
return $this->belongsToMany('App\Comment')->withTimestamps();
}
And finally, Migration file named create_comments_table:
https://pastebin.com/2cHscQfq
My Routes:
https://pastebin.com/ki8FZ0C6
Please help me with this.. I dunno what is wrong
Your foreign keys are wrong. Change your migration to this.
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedInteger('video_id');
$table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
Edit : This adds the comment and attaches it to the video and user.
// model fillable property
protected $fillable = [
'text', 'user_id', 'video_id',
];
// route
Route::post('/film/{id}/komentarz', 'VideosController#postComment');
// controller method
public function postComment(CreateCommentRequest $request, $id)
{
$video = Video::findOrFail($id);
$video->comments()->create([
'text' => $request->text,
'user_id' => auth()->id(),
]);
return 'works';
}
// form
{!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
<div class="form-group">
<div class="col-md-3 control-label">
{!! Form::label('text', 'Treść komentarza:') !!}
</div>
<div class="col-md-8">
{!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-3">
{!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
</div>
</div>
{!! Form::close() !!}
in comment model i see 'user' in fillable, not 'user_id'. i think it should be user_id. or you could use
protected guarded = [];
instead of using fillable array.

Laravel: migration default() field does not work

i having troubles with my migration field default('No description'), i need to save a default value for my null fields on my form, but when i save, my form data stores empty fields.. why? i'm working with Laravel 5.2 and it is my code:
public function up()
{
Schema::create('combos', function (Blueprint $table) {
$table->increments('id');
$table->string('item_name');
$table->string('description')->nullable()->default('No description');
$table->decimal('price', 5, 2);
$table->decimal('buy_price', 5, 2);
$table->timestamps();
});
}
My view:
<div class="form-group">
{!! Form::label('item_name','Item: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('item_name',null,['class'=>'form-control','placeholder'=>'Enter a item name','required','min'=>5]) !!}<br/>
</div>
</div>
<div class="form-group">
{!! Form::label('price','Price: ',['class'=>'control-label col-md-2']) !!}
<div class="col-md-7" >
{!! Form::text('buy_price',null,['class'=>'form-control','placeholder'=>'Enter a price','required']) !!}<br/>
</div>
</div>
in your store function do this
$input = $request->all();
$input['description'] = $request->description;
Combos::create($input);

got error when show data from other table laravel 5.2

i have 2 tables.
users (name, username, email, password, remember_token)
dosen (iddosen, namedosen, address, phonenumber)
i want to show data from 2 tables in 1 view.
my User model :
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
Dosen model :
public function user()
{
return $this->hasOne('App\User');
}
view :
#foreach($dosen as $key => $value)
<strong>Kode Dosen :</strong> {{ $value->profildosen->iddosen }}<br>
<strong>Nama :</strong> {{ $value->profildosen->namedosen}}<br>
<strong>Alamat :</strong> {{ $value->profildosen->address}}<br>
<strong>No HP :</strong> {{ $value->phonenumber}} <br>
<strong>Email :</strong> {{ $value->email }}<br>
#endforeach
method :
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
and got error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dosen.id' in 'where clause' (SQL: select * from `dosen` where `dosen`.`id` is null limit 1) (View: D:\XAMPP\htdocs\infodosenku\resources\views\admin\dosen\index.blade.php)
what is the right method ?
UPDATE
Scheme Database
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username');
$table->string('email')->unique();
$table->string('password', 60);
$table->boolean('admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
Schema::create('dosen', function (Blueprint $table) {
$table->string('id');
$table->string('user_id');
$table->string('nipy');
$table->string('namadosen');
$table->string('alamatdosen');
$table->integer('notelpdosen');
$table->timestamps();
});
Route :
Route::resource('/admin/dosen', 'AdminController',
['except' => ['show']]);
Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Request;
use App\Http\Requests;
use App\Http\Requests\CreateDosenRequest;
use App\Dosen;
use App\User;
use Illuminate\Support\Facades\Input;
use DB;
class AdminController extends Controller
{
public function index()
{
// ambil semua data dosen
$dosen = User::paginate(5);
return view('admin/dosen.index', compact('dosen'));
}
public function create()
{
return view('admin/dosen.create');
}
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => bcrypt($request->input['password']),
'admin' => $request->input('admin')
]);
$dosen = Dosen::create([
'id' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
public function show($id)
{
$dosen = User::find($id);
return view('admin/dosen/show', compact('dosen'));
}
public function edit($id)
{
$dosen = User::find($id);
return view('admin.dosen.edit', compact('dosen'));
}
public function update($id)
{
$dosenUpdate = Request::all();
$dosen = User::find($id);
$dosen->update($dosenUpdate);
return redirect('admin.dosen')->with('message', 'Data berhasil diubah!');
}
public function destroy($id)
{
User::find($id)->delete();
return redirect('admin.dosen')->with('message', 'Data berhasil dihapus!');
}
}
And my View :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Daftar Dosen</div>
<div class="panel-body">
<form class ="form-inline" action="{{ URL('/dosen/hasil/') }}" action="GET">
<div class="form-group">
<label for="cari">Cari Dosen </label>
<input type="text" class="form-control" id="cari" name="cari" placeholder="Masukan Nama Dosen">
</div>
<input class="btn btn-primary" type="submit" value="Cari">
</form><br>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Nama</td>
<td>username</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($dosen as $key => $value)
<tr>
<td>{{ $value->name }}</td>
<td>{{ $value->username}}</td>
<td>
{!! Form::open(['url' => 'dosen/' . $value->id . '/edit', 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'GET') !!}
{{ Form::button('<i class="fa fa-pencil-square-o"></i>', ['type' => 'submit', 'class' => 'btn btn-warning', 'title' => 'Ubah'] ) }}
{!! Form::close() !!}
<button title="Tampilkan" type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal-{{ $value->id }}"><i class="fa fa-share"></i></button>
<!-- Modal -->
<div class="modal fade" id="myModal-{{ $value->id }}" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{ $value->namadosen }}</h4>
</div>
<div class="modal-body" style="overflow:auto;">
<strong>Kode Dosen :</strong> {{ $value->dosen->id }}<br>
<strong>NIP/NIPY :</strong> {{ $value->nipy }}<br>
<strong>Nama :</strong> {{ $value->namadosen }}<br>
<strong>Alamat :</strong> {{ $value->alamatdosen }}<br>
<strong>No HP :</strong> {{ $value->notelpdosen }} <br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{!! Form::open(['url' => 'dosen/' . $value->id, 'style'=>'display:inline-block']) !!}
{!! Form::hidden('_method', 'DELETE') !!}
{{ Form::button('<i class="fa fa-trash"></i>', ['type' => 'submit', 'class' => 'btn btn-danger', 'title' => 'Hapus'] ) }}
{!! Form::close() !!}
{!! Form::model($value, ['route' => ['admin.dosen.update', $value->id], 'method' => 'PUT']) !!}
</td>
</tr>
#endforeach
</tbody>
</table>
<h5><span class="label label-default">
Showing {!! $dosen->count() !!} results from total {!! $dosen->total() !!} results.
</span></h5>
<div> {!! $dosen->links() !!} </div>
</div>
</div>
</div>
</div>
</div>
#endsection
Dosen Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Dosen extends Model
{
protected $table = 'dosen';
protected $fillable = ['iddosen', 'namadosen', 'user_id', 'nipy', 'kodeprogdidosen','alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'agamadosen', 'emaildosen', 'sandidosen', 'jkldosen', 'fotodosen'];
protected $casts = [
'iddosen' => 'varchar',
];
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
}
User Model :
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', 'email', 'password', 'admin',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profildosen()
{
return $this->belongsTo('App\Dosen');
}
}
From Laravel Docs
Eloquent determines the default foreign key name by examining the name
of the relationship method and suffixing the method name with _id.
Your function name is profiledosen so Laravel will assume that in your in your Dosen Table you have id field as primary identifier.
You can change it from iddosen to id only and then change your method name to
public function dosen()
{
return $this->belongsTo('App\Dosen');
}
Alternatively you can supply the custom primary key to your method like
public function profildosen()
{
return $this->belongsTo('App\Dosen', 'iddosen');
}
The reason is that you badly identify your table id a so instead of dosen.id you should use dosen.iddosen
So the query should be like this: select * from dosen where iddosen is null limit 1
Or you may to use Laravel Query Builder More.
But the most important thing is that you need to know on what columns you will join your tables.
Hope it will help

Categories