Data not pulling through to form - laravel - php

I am trying to pull data from a form and as per my screenshot below the data will not display, but it appears to be functioning to a certain extent as there are two users which exist in my instructor variable and there are two options to select from, can anyone help?
create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
#if (Auth::user()->isAdmin())
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $Instructor, Input::get('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
#if($errors->has('Instructor'))
<p class="help-block">
{{ $errors->first('Instructor') }}
</p>
#endif
</div>
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
#endif
</form>
</div>
</div>
#endsection
CoursesController
protected function create()
{
{
$Instructor = \App\User::whereHas('role', function ($q) { $q->where('role_id', 2); } )->get()->pluck('title', 'id');
// $courses = Course::all()->pluck('title');
return view('admin.courses.create', compact('Instructor'));
}
}
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsToMany(Role::class, 'role_user');
}
public function isAdmin()
{
return $this->role()->where('role_id', 1)->first();
}
public function roles(){
return $this->belongsToMany('App\Role');
}
Thanks for any help.

The Laravel Collective Form::select requires the values to be in a [ key => value ] array pair. You are passing it a result collection.
You need to translate the result of $Instructor = \App\User::whereHas('role', function ($q) { $q->where('role_id', 2); } )->get()->pluck('title', 'id'); to an array that is (I assume) [ id => title, id => title ]...
So, before you pass it to your view something like this:
$flatInstructors = []
$Instructor->each(function($item, $key) {
$flatInstructors[$item->id] = $item->title;
});
return view('admin.courses.create', compact('flatInstructors'));
And use $flatInstructors in your Form::select generation.

Related

Laravel 5.8: Call to a member function update() on null

I'm currently learning Laravel 5.8 and creating instagram clone app and I've been having an issue with updating my profile details. Whenever I hit "Update profile", it gives off an error - "Call to a member function update() on null". The issue seems to be in public function update(). I've looked up other threads and can't seem to fix this issue, so any help would be greatly appreciated!
Here's my code:
View:
#section('content')
<div class="container">
<form action="/profile/{{ $user->id }}" enctype="multipart/form-data" method="post" >
#csrf
#method('PATCH')
<div class="row">
<div class="col-8 offset-2">
<div class="row pb-3">
<h1>Edit profile</h1>
</div>
<div class="form-group row">
<label for="title" class="col-form-label"><strong>Title</strong></label>
<input id="title" type="text" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') ?? $user->profile['title'] }}" required autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $title }}</strong>
</span>
#enderror
</div>
<div class="form-group row">
<label for="description" class="col-form-label"><strong>Description</strong></label>
<input id="description" type="text" class="form-control #error('description') is-invalid #enderror" name="description" value="{{ old('description') ?? $user->profile['description']}}" required autocomplete="description" autofocus>
#error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $description }}</strong>
</span>
#enderror
</div>
<div class="row">
<label for="photo" class="col-form-label">Select Profile Picture</label>
<input type="file" class="form-control-file" id="photo" name="photo">
#error('photo')
<strong>{{ $message }}</strong>
#enderror
</div>
<div class="row pt-3">
<button class="btn btn-primary">
Update Profile
</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Route:
Auth::routes();
Route::get('/profile/{user}', 'ProfileController#index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfileController#edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfileController#update')->name('profile.update');```
Controller:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProfileController extends Controller
{
public function index(User $user){
return view('profile.index', [
'user' => $user,
]);
}
public function edit(User $user){
return view('profile.edit', [
'user' => $user,
]);
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
auth()->user()->profile->update($data);
return redirect("/storage/ {$user->id}");
}
}
Thank you in advance!
try passing the user you are editing as you have passed them in the routes., The error means you want to update a user but you haven't specified which user you are updating.
try doing something like this:
public function validateUser(){
return request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
}
then in the update function do something like this:
public function update($user_id){
return User::where('id',$user_id)->update($this->validateUser());
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
$user->profile()->update($data);
return redirect("/storage/".$user->id);
}
Update Or Insert
Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used.
User::where('id',$id)->updateOrInsert($data);

Laravel - Undefined variable: Instructor

I am trying to pass users with a specific role_id through a form on a create.blade.php see below;
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="panel-body">
#if (Auth::user()->isAdmin())
<div class="row">
<div class="col-xs-12 form-group">
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $Instructor, old('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
<p class="help-block"></p>
#if($errors->has('Instructor'))
<p class="help-block">
{{ $errors->first('Instructor') }}
</p>
#endif
</div>
</div>
#endif
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</form>
</div>
</div>
#endsection
User.php
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsToMany(Role::class, 'role_user');
}
public function isAdmin()
{
return $this->role()->where('role_id', 1)->first();
}
public function roles(){
return $this->belongsToMany('App\Role');
}
CoursesController.php
My create function:
protected function create()
{
{
$Instructor = \App\User::whereHas('role', function ($q) { $q->where('role_id', 2); } )->get()->pluck('title', 'id');
// $courses = Course::all()->pluck('title');
return view('admin.courses.create', compact('courses'));
}
}
The following error is being returned:
Undefined variable: Instructor (View:
C:\xampp\htdocs\test\resources\views\admin\courses\create.blade.php)
I am not sure where I have gone wrong. Thanks for any help.
Referring to my latest comment:
In the controller, you missing pass Instructor to your view:
return view('admin.courses.create', compact('courses', 'Instructor'));

Success and error message does'nt show

Hello i am new to laravel i created page to added single post but for some reason success and errors messages doesn't appear at all not matter i successfully insert a new post or submit empty form although some fields are required .. in my controller i am using this method postCreatePost
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Catgory;
class PostController extends Controller {
public function getBlogIndex() {
return view ('frontend.blog.index');
}
public function getSignlePost($post_id, $end = 'frontend') {
return view ($end, '.blog.single');
}
public function getCreatePost() {
return view('admin.blog.create_post');
}
public function postCreatePost(Request $request) {
$this->validate($request, [
'title' => 'required|max:120|unique:posts',
'author' => 'required|max:80',
'body' => 'required'
]);
$post = new Post();
$post->title = $request['title'];
$post->author = $request['author'];
$post->body = $request['body'];
$post->save();
//Attaching categories
return redirect()->route('admin.index')->with(['success','Post sucessfully created!']);
}
}
This is my view
#extends('layouts.admin-master')
#section('styles')
<link rel="stylesheet" href="{{ URL::secure('src/css/form.css') }}" type="text/css" />
#endsection
#section('content')
<div class="container">
#section('styles')
<link rel="stylesheet" href="{{ URL::to('src/css/common.css') }}" type="text/css" />
#append
#if(Session::has('fail'))
<section class="info-box fail">
{{ Session::get('fail') }}
</section>
#endif
{{ var_dump(Session::get('success')) }}
#if(Session::has('success'))
<section class="info-box success">
{{ Session::get('success') }}
</section>
#endif
#if(count($errors) > 0)
<section class="info-box fail">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</section>
#endif
<form action="{{ route('admin.blog.post.create') }}" method="post">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" {{ $errors->has('title') ? 'claass=has-error' : '' }} />
</div>
<div class="input-group">
<label for="author">Author</label>
<input type="text" name="author" id="author" {{ $errors->has('author') ? 'claass=has-error' : '' }} />
</div>
<div class="input-group">
<label for="category_select">Add Categories</label>
<select name="category_select" id="category_select">
<!-- Foreach loop to output categories -->
<option value="Dummy Category ID">Dummy Category</option>
</select>
<button type="button" class="btn">Add Category</button>
<div class="added-categories">
<ul></ul>
</div>
</div>
<input type="hidden" name="categories" id="categories">
<div class="input-group">
<label for="body">Body</label>
<textarea name="body" id="body" cols="30" rows="10" {{ $errors->has('body') ? 'claass=has-error' : '' }}></textarea>
</div>
<button type="submit" class="btn">Create Post</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
</div>
#endsection
#section('scripts')
<script type="text/javascript" src="{{ URL::secure('src/js/posts.js') }}"></script>
#endsection
My routes inside web middleware
Route::group(['middleware' => ['web']], function () {
Route::get('/about', function() {
return view('frontend.other.about');
})->name('about');
Route::group([
'prefix' => '/admin'
], function() {
Route::get('/', [
'uses' => 'AdminController#getIndex',
'as' => 'admin.index'
]);
Route::get('/blog/posts/create', [
'uses' => 'PostController#getCreatePost',
'as' => 'admin.blog.create_post'
]);
Route::post('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
});
});
And the model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function categories() {
return $this->belongsToMany('App\Category', 'posts_categories');
}
}
You're using wrong syntax. Try this one:
return redirect()->route('admin.index')->with('success','Post sucessfully created!');

Laravel Form Update can't get the right value

so i make laravel form for update
Index.blade
<div class="col-sm-12">
<div class="formrow row">
<div class="form-group">
<div class="divlabel col-sm-2">
<label>Kode Program Studi:</label>
<span class="required">*</span>
</div>
<div class="divinput col-sm-8">
<select id="id" data-plugin-selectTwo class="form-control populate placeholder" title="kode program studi harus diisi" name='id' required data-plugin-selecTwo>
<option value="">-PILIH NAMA USER-</option>
#foreach ($users as $user)
<option class="form-control" value = '{{$user->id}}'>{{$user->id.' | '.$user->name}}</option>
#endforeach
<label class="error" for="id"></label>
</select>
</div>
</div>
{!! Form::open(['url' => 'master/hakakses/'.$user->id,'method' => 'PATCH','class'=>'update']) !!}
<!-- {!! Form::model($user,['route'=>['master.hakakses.update', $user->id],'method' => 'PATCH','class'=>'update']) !!} -->
<div class="form-group">
<div class="divlabel col-sm-2">
<label>Kode Program Studi:</label>
<span class="required">*</span>
</div>
<div class="divinput col-sm-8">
<select id="role" data-plugin-selectTwo class="form-control populate placeholder" title="kode program studi harus diisi" name='role_id' required data-plugin-selecTwo>
<option value="">-PILIH HAK AKSES-</option>
#foreach ($roles as $role)
<option class="form-control" value = '{{$role->id}}'>{{$role->id.' | '.$role->role_akses.' | '.$role->role_name}}</option>
#endforeach
<label class="error" for="role"></label>
</select>
</div>
</div>
</div>
<div class="col-sm-offset-4 col-sm-50">
<input type="submit" value="Ubah" name = 'simpan' class = 'btn btn-primary'>
<td>Kembali</td>
</div>
</div>
{!! Form::close() !!}
Controller :
public function index()
{
$data=new HakAkses;
$users= $data->ListUser();
$roles= $data->ListRole();
return view ('Master.HakAkses.index',compact ('users','roles'));
}
public function update(Request $request, $id)
{
return $id;
}
Model:
public static function ListUser()
{
$table = DB::select( DB::raw("SELECT * FROM users"));
return $table;
}
public static function ListRole()
{
$table = DB::select( DB::raw("SELECT * FROM m_role"));
return $table;
}
The problem is I can't get the value of {{$role->id}} when I try to return $id , the value is the latest input of id in the database. I think the problem is in the FORM:
{!! Form::open(['url' => 'master/hakakses/'.$user->id,'method' => 'PATCH','class'=>'update']) !!}
Can anyone please help me?
I see the problem is that you're passing here:
{!! Form::open(['url' => 'master/hakakses/'.$user->id,'method' => 'PATCH','class'=>'update']) !!}
the $user->id but you want to get in your controller {{$role->id}}
So the solvation is in your controller to:
public function update(Request $request, $id)
{
// $id is a user's id
$roleId = $request->input('role_id');
}

Laravel use same form for create and edit

Am quite new to Laravel and I have to create a form for create and a form for edit. In my form I have quite some jquery ajax posts. Am wondering whether Laravel does provide for an easy way for me to use the same form for my edit and create without having to add tons of logic in my code. I don't want to check if am in edit or create mode every time when assigning values to fields when the form loads. Any ideas on how I can accomplish this with minimum coding?
I like to use form model binding so I can easily populate a form's fields with corresponding value, so I follow this approach (using a user model for example):
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{-- More fields... --}}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
So, for example, from a controller, I basically use the same form for creating and updating, like:
// To create a new user
public function create()
{
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user (load to edit)
public function edit($id)
{
$user = User::find($id);
// Load user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Pretty easy in your controller you do:
public function create()
{
$user = new User;
$action = URL::route('user.store');
return View::('viewname')->with(compact('user', 'action'));
}
public function edit($id)
{
$user = User::find($id);
$action = URL::route('user.update', ['id' => $id]);
return View::('viewname')->with(compact('user', 'action'));
}
And you just have to use this way:
{{ Form::model($user, ['action' => $action]) }}
{{ Form::input('email') }}
{{ Form::input('first_name') }}
{{ Form::close() }}
For the creation add an empty object to the view.
return view('admin.profiles.create', ['profile' => new Profile()]);
Old function has a second parameter, default value, if you pass there the object's field, the input can be reused.
<input class="input" type="text" name="name" value="{{old('name', $profile->name)}}">
For the form action, you can use the correct endpoint.
<form action="{{ $profile->id == null ? '/admin/profiles' : '/admin/profiles/' . $profile->id }} " method="POST">
And for the update you have to use PATCH method.
#isset($profile->id)
{{ method_field('PATCH')}}
#endisset
Another clean method with a small controller, two views and a partial view :
UsersController.php
public function create()
{
return View::('create');
}
public function edit($id)
{
$user = User::find($id);
return View::('edit')->with(compact('user'));
}
create.blade.php
{{ Form::open( array( 'route' => ['users.index'], 'role' => 'form' ) ) }}
#include('_fields')
{{ Form::close() }}
edit.blade.php
{{ Form::model( $user, ['route' => ['users.update', $user->id], 'method' => 'put', 'role' => 'form'] ) }}
#include('_fields')
{{ Form::close() }}
_fields.blade.php
{{ Form::text('fieldname1') }}
{{ Form::text('fieldname2') }}
{{ Form::button('Save', ['type' => 'submit']) }}
Simple and clean :)
UserController.php
public function create() {
$user = new User();
return View::make('user.edit', compact('user'));
}
public function edit($id) {
$user = User::find($id);
return View::make('user.edit', compact('user'));
}
edit.blade.php
{{ Form::model($user, ['url' => ['/user', $user->id]]) }}
{{ Form::text('name') }}
<button>save</button>
{{ Form::close() }}
For example, your controller, retrive data and put the view
class ClassExampleController extends Controller
{
public function index()
{
$test = Test::first(1);
return view('view-form',[
'field' => $test,
]);
}
}
Add default value in the same form, create and edit, is very simple
<!-- view-form file -->
<form action="{{
isset($field) ?
#route('field.updated', $field->id) :
#route('field.store')
}}">
<!-- Input case -->
<input name="name_input" class="form-control"
value="{{ isset($field->name) ? $field->name : '' }}">
</form>
And, you remember add csrf_field, in case a POST method requesting. Therefore, repeat input, and select element, compare each option
<select name="x_select">
#foreach($field as $subfield)
#if ($subfield == $field->name)
<option val="i" checked>
#else
<option val="i" >
#endif
#endforeach
</select>
Instead of creating two methods - one for creating new row and one for updating, you should use findOrNew() method. So:
public function edit(Request $request, $id = 0)
{
$user = User::findOrNew($id);
$user->fill($request->all());
$user->save();
}
Article is a model containing two fields - title and content
Create a view as pages/add-update-article.blade.php
#if(!isset($article->id))
<form method = "post" action="add-new-article-record">
#else
<form method = "post" action="update-article-record">
#endif
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="Enter title" name="title" value={{$article->title}}>
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control" rows="5" id="content" name="content">
{{$article->content}}
</textarea>
<span class="text-danger">{{ $errors->first('content') }}</span>
</div>
<input type="hidden" name="id" value="{{{ $article->id }}}">
<button type="submit" class="btn btn-default">Submit</button>
</form>
Route(web.php): Create routes to controller
Route::get('/add-new-article', 'ArticlesController#new_article_form');
Route::post('/add-new-article-record', 'ArticlesController#add_new_article');
Route::get('/edit-article/{id}', 'ArticlesController#edit_article_form');
Route::post('/update-article-record', 'ArticlesController#update_article_record');
Create ArticleController.php
public function new_article_form(Request $request)
{
$article = new Articles();
return view('pages/add-update-article', $article)->with('article', $article);
}
public function add_new_article(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
Articles::create($request->all());
return redirect('articles');
}
public function edit_article_form($id)
{
$article = Articles::find($id);
return view('pages/add-update-article', $article)->with('article', $article);
}
public function update_article_record(Request $request)
{
$this->validate($request, ['title' => 'required', 'content' => 'required']);
$article = Articles::find($request->id);
$article->title = $request->title;
$article->content = $request->content;
$article->save();
return redirect('articles');
}
In Rails, it has form_for helper, so we could make a function like form_for.
We can make a Form macro, for example in resource/macro/html.php:
(if you don't know how to setup a macro, you can google "laravel 5 Macro")
Form::macro('start', function($record, $resource, $options = array()){
if ((null === $record || !$record->exists()) ? 1 : 0) {
$options['route'] = $resource .'.store';
$options['method'] = 'POST';
$str = Form::open($options);
} else {
$options['route'] = [$resource .'.update', $record->id];
$options['method'] = 'PUT';
$str = Form::model($record, $options);
}
return $str;
});
The Controller:
public function create()
{
$category = null;
return view('admin.category.create', compact('category'));
}
public function edit($id)
{
$category = Category.find($id);
return view('admin.category.edit', compact('category'));
}
Then in the view _form.blade.php:
{!! Form::start($category, 'admin.categories', ['class' => 'definewidth m20']) !!}
// here the Form fields
{{!! Form::close() !!}}
Then view create.blade.php:
#include '_form'
Then view edit.blade.php:
#include '_form'
You can use form binding and 3 methods in your Controller. Here's what I do
class ActivitiesController extends BaseController {
public function getAdd() {
return $this->form();
}
public function getEdit($id) {
return $this->form($id);
}
protected function form($id = null) {
$activity = ! is_null($id) ? Activity::findOrFail($id) : new Activity;
//
// Your logic here
//
$form = View::make('path.to.form')
->with('activity', $activity);
return $form->render();
}
}
And in my views I have
{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}
Here is simple way to create or edit record using same form .
I have created form.blade.php file for create and edit
#extends('layouts.admin')
#section('content')
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Create User</h6>
</div>
<div class="card-body">
<form method="post" action="{{isset($user)? route('users.update',$user->id):route('users.store')}}">
#csrf
#if (isset($user))
#method('PUT')
#endif
<div class="row mb-3">
<div class="col-md-4">
<label>Name</label>
<input class="form-control #error('name') is-invalid #enderror" value="{{isset($user->name) ? $user->name: old('name')}}" type="text" name="name" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-4">
<label>Email address</label>
<input class="form-control #error('email') is-invalid #enderror" value="{{isset($user->email) ? $user->email:old('email')}}" type="email" name="email" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-4">
<label>Password</label>
<input class="form-control #error('password') is-invalid #enderror" value="{{old('password')}}" type="text" name="password" required>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-3">
<button class="btn btn-sm btn-success btn-icon-split">
<span class="text">Save</span>
</button>
<a href="{{route('users.index')}}" class="btn btn-sm btn-dark btn-icon-split">
<span class="text">Cancel</span>
</a>
</div>
</form>
</div>
</div>
#endsection
And in my controller
public function create()
{
return view('admin.user.form');
}
public function edit($id){
$user= User::find($id);
return view('admin.user.form', compact('user'));
}
UserController.php
use View;
public function create()
{
return View::make('user.manage', compact('user'));
}
public function edit($id)
{
$user = User::find($id);
return View::make('user.manage', compact('user'));
}
user.blade.php
#if(isset($user))
{{ Form::model($user, ['route' => ['user.update', $user->id], 'method' => 'PUT']) }}
#else
{{ Form::open(['route' => 'user.store', 'method' => 'POST']) }}
#endif
// fields
{{ Form::close() }}
I hope this will help you!!
form.blade.php
#php
$name = $user->name ?? null;
$email = $user->email ?? null;
$info = $user->info ?? null;
$role = $user->role ?? null;
#endphp
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', $name, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', $email, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('role', 'Função') !!}
{!! Form::text('role', $role, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('info', 'Informações') !!}
{!! Form::textarea('info', $info, ['class' => 'form-control']) !!}
</div>
<a class="btn btn-danger float-right" href="{{ route('users.index') }}">CANCELAR</a>
create.blade.php
#extends('layouts.app')
#section('title', 'Criar usuário')
#section('content')
{!! Form::open(['action' => 'UsersController#store', 'method' => 'POST']) !!}
#include('users.form')
<div class="form-group">
{!! Form::label('password', 'Senha') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Confirmação de senha') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>
{!! Form::submit('ADICIONAR', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}
#endsection
edit.blade.php
#extends('layouts.app')
#section('title', 'Editar usuário')
#section('content')
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'PUT']) !!}
#include('users.form', compact('user'))
{!! Form::submit('EDITAR', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Editar senha
#endsection
UsersController.php
use App\User;
Class UsersController extends Controller {
#...
public function create()
{
return view('users.create';
}
public function edit($id)
{
$user = User::findOrFail($id);
return view('users.edit', compact('user');
}
}
use any in the route
Route::any('cr', [CreateContent::class, 'create_content'])
->name('create_resource');
in controller use
User::UpdateOrCreate([id=>$user->id], ['field_name'=>value, ...]);

Categories