Edit two unique value with laravel - laravel

I have a problem with my Laravel 5.8 project. I want to edit one of two field that both have unique value.
Blade:
#extends('layouts.master')
#section('content')
<h1>CHANGE SURGICAL DIVISION</h1>
<a href="/surgical-div">
<button type="button" class="btn btn-primary btn-sm">BACK</button><br>
</a>
#if (session('mess'))
<div class="alert alert-success">
{{ session('mess')}}
</div>
#endif
<form method="POST" action="/surgical-div/{{ $surgicaldivs->id_surgical_div }}">
#method('patch')
#csrf
<div class="form-group">
<label for="name_surgical_div">Surgical Division Name: </label>
<input type="text" value="{{ $surgicaldivs->name_surgical_div }}"
class="form-control #error('name_surgical_div') is-invalid #enderror" id="name_surgical_div" name="name_surgical_div"
placeholder="Insert The Surgical Division">
#error('name_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="form-group">
<label for="initial_surgical_div">Surgical Division Initial : </label>
<input type="text" value="{{ $surgicaldivs->initial_surgical_div }}"
class="form-control #error('initial_surgical_div') is-invalid #enderror" id="initial_surgical_div" name="initial_surgical_div"
placeholder="Insert Surgical Division Initial">
#error('initial_surgical_div')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-success btn-sm">Save</button>
</form>
#endsection
Controller:
public function edit($id)
{
$surgicaldivs = SurgicalDiv::withTrashed()->find($id);
return view('pages.surgical_div.surgical_div_edit', compact('surgicaldivs'));
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SurgicalDiv extends Model
{
//Table Name
protected $table = 'surgical_div';
// Primary Key
protected $primaryKey = 'id_surgical_div';
//Soft Deletes
use SoftDeletes;
//Fillable Field
protected $fillable = ['name_surgical_div', 'initial_surgical_div'];
}
This is the update in the controller that i've tried :
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div',
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div'
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
I don't know what to put on the update function in the controller. I want to update one or even both of the field from my blade.

Try this
public function update(Request $request, SurgicalDiv $SurgicalDiv)
{
$request->validate([
'name_surgical_div' => 'required|unique:surgical_div,name_surgical_div,'.$id,
'initial_surgical_div' => 'required|unique:surgical_div,initial_surgical_div,'.$id
]);
SurgicalDiv::withTrashed()->where('id_surgical_div',$id)
->update([
'name_surgical_div' => $request->name_surgical_div,
'initial_surgical_div' => $request->initial_surgical_div
]);
return redirect('/surgical-div/'.$id.'/edit')->with('mess',' Surgical Division Change Success !');
}
This will check the table for same entries except the row with the $id. This way you can check if there are any other rows with same values in the two columns.

Related

Eloquent relationship through 2 models

I have Post model:
class Post extends Model
{
use HasFactory;
protected $fillable = [
'category_id',
'user_id',
'img',
'title',
'content',
];
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
public function comments(){
return $this->hasMany(Comment::class)->where('parent_id', '0');
}
}
Comments model:
class Comment extends Model
{
use HasFactory;
protected $fillable = [
'post_id',
'user_id',
'parent_id',
'content',
// 'img'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function replies()
{
return $this->hasMany(Comment::class,'parent_id');
}
}
Can I use the replies function via the post model?
For example:
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#endforeach
I am just trying to add replies to comments.
<div class="col-md-12">
<div class="blog-comment">
<hr/>
<ul class="comments">
<li class="clearfix">
#foreach($post as $comments)
#foreach($comments->comments->sortByDesc('id') as $comment)
<img src="https://bootdey.com/img/Content/user_1.jpg" class="avatar">
<div class="post-comments">
<p class="meta d-flex justify-content-between">{{ $comments->user->name }}<span>{{ $comments->user->created_at }}</span></p>
<p>
{{ $comment->content }}
</p>
</div>
<form action="{{ route('comment.store') }}" method="POST" class="w-100">
#csrf
<div class="replyform d-flex mb-3">
<input type="hidden" name="post_id" value="{{ $comments->id }}">
<input type="hidden" name="parent_id" value="{{ $comment->id }}">
<input class="d-block ml-auto w-50 align-top" type="text" name="content" required>
<button type="submit" class="offset replysub fas fa-paper-plane ml-1"></button>
</div>
</form>
#endforeach
#endforeach
#foreach($comments->comments->replies->sortByDesc('id') as $comment)
#if($comment->parent_id !== 0)
<ul class="comments">
<li class="clearfix">
<img src="https://bootdey.com/img/Content/user_3.jpg" class="avatar">
<div class="post-comments">
<p class="meta">Dec 20, 2014 JohnDoe says : <i class="pull-right"><small>Reply</small></i></p>
<p>
{{ $comment->content }}
</p>
</div>
<input class="replyform d-block ml-auto mb-3 w-50" type="text" name="" value="">
</li>
</ul>
#endif
#endforeach
</li>
</ul>
</div>
</div>
Of course, I can take and pass one more variable to the template, but I heard that you shouldn't do this, it overloads the controller. Therefore, I try to do it through an eloquent relationship.
P.S. Or is there a way to do it in the post model? Like:
public function replies(){
return $this->hasMany(Comment::class)->where('parent_id', 'id(of parent comment)');
}

My login form only reloads the page but doesn't log the user in

My login form is broken after I took out the "email" and "name" from the form, took out "email" and "name" from protected fillable in User.php. I also made the redundant fields nullable in the database. The user should be able to login using their "username" and "password". The registration form works fine, its just the login form that is causing issue.
login.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>
<div class="col-md-6">
<input id="username" type="username" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
The model User.php
namespace App;
use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'username', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function following()
{
return $this->belongsToMany(Profile::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
public function tasks()
{
return $this->hasMany(Task::class);
}
}
The database table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
LoginController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Add this function to App\Http\Controller\Auth\LoginController.php.
It will change your login field email to username. which will solve your problem for now.
public function username()
{
return 'username';
}
One suggestion for you. have a look on "how to use authentication of a framework."

"Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)"

When I am editing my post then I am prompted with the following error message
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\CERCAA\resources\views\admin\posts\edit.blade.php)
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'content' => 'required',
'category_id' => 'required'
]);
$post = Post::find($id);
if($request->hasFile('featured'))
{
$featured = $request->featured;
$featured_new_name = time() . $featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post->featured = 'uploads/posts/'.$featured_new_name;
}
$post->title = $request->title;
$post->content = $request->content;
$post->category_id = $request->category_id;
$post->save();
Session::flash('success', 'Post updated successfully.');
return redirect()->route('posts');
}
and blade code
<div class="form-group">
Select a Category
#foreach($categories as $category)
id}}"
#if($post->$category->id == $category->name)
selected
#endif
{{$category->name}}
#endforeach
List item
My Post method for post and category
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; // here set table's name
protected $primaryKey = 'id'; // here set table's primary Key field name
protected $fillable = ['id']; // here set all table's fields name
public function posts()
{
return $this->hasMany('App\Post');
}
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
public function category()
{
return $this->belongsTo('App/Category');
}
public function getFeaturedAttribute($featured)
{
return asset($featured);
}
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable=['title','content','category_id','featured','slug'];
}
}
Edit.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-header bg-info">
<div class="text-center">
<h4 class="m-b-0 text-white">
<div class="panel panel-default">
<div class="panel-heading">
Edit Post:{{$post->title}}
</div>
<div class="panel-body">
<form action="{{route('post.update', ['id'=>$post->id])}} " method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for ="title">Title</label>
<input type="text" name="title" class="form-control" value="{{$post->title}}">
</div>
<div class="form-group">
<label for ="featured">Featured image</label> <input type="file" name="featured" class="form-control">
</div>
<div class="form-group">
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for ="content">Content</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$post->content}}</textarea>
</div>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit"> Update Post</button>
</div>
</div>
</form>
</div>
</div>
</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Row -->
#stop
Controller...
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|mimes:jpeg,pdf,docx,png:5000',
'file'=>'required|mimes:jpeg,pdf,docx,png:5000',
'content'=>'required',
'category_id'=>'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file_name=time().$file->getClientOriginalName();
$file->move('uploads/posts', $file_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/posts'. $file_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
This the area in your blade where you are getting the issue:
<label for ="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $category)
<option value="{{$category->id}}"
#if(property_exists($post, 'category') && $post->$category['id'] == $category->name)
selected
#endif
>{{$category->name}}</option>
#endforeach
</select>
Where are you fetching and providing $categories to this blade template? I mean the controller method which loads the edit blade?
Can you post that code as well?
And please update your question instead of posting answers.

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'pk5.roles' doesn't exist

I am able to insert records to employee_roles through tinker but unable to insert them through code
Role.php
<?php
namespace App\Models\Admin\Employee;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $table = 'employee_roles';
public function permissions()
{
return $this->belongsToMany('App\Models\Admin\Employee\Permission', 'employee_permission_role', 'role_id', 'permission_id');
}
}
RoleController.php
<?php
namespace App\Http\Controllers\Admin\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Employee\Employee;
use App\Models\Admin\Employee\Role;
use App\Models\Admin\Employee\Permission;
class RoleController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function index()
{
$roles = Role::all();
return view('admins.employees.roles.role', compact('roles'));
}
public function create()
{
$permissions = Permission::all();
return view('admins.employees.roles.create',compact('permissions'));
}
public function store(Request $request)
{
//dd($request);
$this->validate($request, [
'name' => 'required|unique:roles'
]);
$role = new Role();
$role->name = $request['name'];
$role->save();
$role->permissions()->sync($request->permission);
return redirect(route('admin.employee.role.index'));
}
admins.employees.roles.create.blade.php
#extends('layouts.admin')
#section('title', 'Role - Create')
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Add an Employee Role</h1>
<br><br>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('admin.employee.role.store') }}" method="post">
#csrf
<div class="form-group">
<label for="name">Role Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Role Name" value="{{ old('name') }}">
</div>
<div class="form-row">
<div class="col-md-4">
<label for="name"><b>Customer Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Customer')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
<div class="col-md-4">
<label for="name"><b>Despatch Permissions</b></label>
#foreach ($permissions as $permission)
#if ($permission->for == 'Despatch')
<div class="checkbox">
<label><input type="checkbox" name="permission[]" value="{{ $permission->id }}">{{ $permission->name }}</label>
</div>
#endif
#endforeach
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
Back
</div>
</form>
#endsection
#section('pagescript')
#stop
$this->validate($request, [
'name' => 'required|unique:roles'
]);
You should fix table name as employee_roles
Because you don't have table as roles you said that in your Role model you're using employee_roles table ( protected $table = 'employee_roles';)

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Resources