edit form does not display values to edit in laravel 5 - laravel-5.4

I am trying to create CRUD application in Laravel 5.4 but and i am done with create and display form now remaining edit and delete but the edit form does display information instead it it brings a create form and creates a new record instead of create . Any help would be appreciated.Below is my controller
<?php
namespace App\Http\Controllers;
use \App\Http\Requests\contactsrequest;
use App\contacts; // contacts model included using "use"
class contactscontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//Display Data
//find contact by contacts model
// use model contacts and include the use App\contacts model
// variable contact holds all values of contacts table
$contact=contacts::all(); // contavt
return view('contacts.index',['contacts'=>$contact]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('contacts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(contactsrequest $request)
{
//contacts model
contacts::create($request->all());
return redirect()->route('contacts.index')->with('message', 'Contacts has been added successfully');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(contacts $contacts)
{
//
return view('contacts.edit', compact('contacts'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(contactsrequest $request, contacts $contacts)
{
//
$contacts->update($request->all());
return redirect()->route('contacts.index')->with('message', 'Contacts has been updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
The edit form is below
<!-- Home page to Display contacts -->
#extends('master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Update Contacts</h3>
</div>
<div class="panel-body">
<!-- $contacts is object -->
{{Form::model($contacts, array('route'=>['contacts.update', $contacts->id],'method'=>'POST'))}}
<!-- input name, value is null, the parameters e.g class, placeholder etc -->
<div class="form-group">
{{Form:: label('Name','Enter name') }}
{{Form:: text('Name',null, ['class'=>'form-control','placeholder'=>'Enter Name']) }}
</div>
<div class="form-group">
{{Form:: label('Phone','Mobile Number') }}
{{Form:: text('Phone',null, ['class'=>'form-control','placeholder'=>'Enter Mobile Number']) }}
</div>
<div class="form-group">
{{Form:: label('Email','Email Address') }}
{{Form:: email('Email', null, ['class'=>'form-control','placeholder'=>'Enter Email Address']) }}
</div>
<div class="form-group">
{{ Form::button('Update',['class'=>'btn btn-primary', 'type'=>'submit'] )}}
|
<i class="fa fa-plus-square fa-lg" aria-hidden="true" style="border: none;"></i>Back
</div>
{{Form:: close() }}
</div>
</div>
</div>
</div>
</div>
#endsection

try this in your controller
public function edit($id)
{
$contacts = Contacts::findOrFail($id);
Return to view ('contacts. edits', compact ('contacts'));
}

your view expects the model to be called $contacts, so change your edit() method in the controller to be the following:
public function edit($id)
{
$contact = Contacts::findOrFail($id);
return view('contacts.edit', ['contacts' => $contact]);
}

Related

How to check user activeness (from database) before login in Laravel

In my application, there is a 'status' column in the 'users' table. Which indicates the user activeness. Now I want to check the activeness of the user before login to the system and give a message if he is deactivated. How to do this? There are several answers here, but I cannot make this work with the help of those answers.
This is my LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Create a middleware class to check the status column. For example:
<?php namespace App\Http\Middleware;
use Closure;
class CheckStatusMiddleware {
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = User::where('email', $request->input('email'))->firstOrFail();
if (!$user->active)
{
return redirect('home');
}
return $next($request);
}
}
Then register the class and apply it to the necessary route(s).
See Middleware for more information.
You can use authenticated() method.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// Check status
if ($user->status == 'inactive') {
$this->logout($request);
// Send message
throw ValidationException::withMessages([
$this->username() => [__('Your status is inactive')],
]);
}
}
}

Trying to get property of non-object ErrorException (E_NOTICE)

I am trying to isert data in mysql using laravel, while I am getting the error ErrorException (E_NOTICE)
Trying to get property of non-object, where is the problem I dont know please help me.
my controller code is PublicationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\publication;
use Auth;
class PublicationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('publications');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
publications::create([
'user_id' => Auth::user()->id,
'title' => request('title'),
'status' => request('status'),
'year' => request('research_area')
]);
return 'inserted';
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
While model code is given publication.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class publication extends Model
{
//
protected $fillable = ['title','status','year'];
}
The code of my route is given.
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('education', 'EducationController#index');
Route::post('edu', 'EducationController#store');
Route::get('publications','PublicationController#index');
Route::post('pub','PublicationController#store');
The error is given Class ErrorException (E_NOTICE)
Trying to get property of non-object please help if any one know where is the problem
Consider placing PublicationController behind authentication middleware:
class PublicationController extends Controller
{
...
public function __construct()
{
$this->middleware('auth');
}
...
}
You can also use route groups:
Route::middleware(['auth'])->group(function () {
// your routes
});
If Auth::user() is null then Auth::user()->id will give you the exception you mentioned. Placing the routes or controller behind the middleware should solve this.
Edit
This assumes you are using Laravel 5.6 https://laravel.com/docs/5.6. This should work for 5.5 and 5.7.
Finally I found the answer of my question by just including 'user_id' in my model fillable arry and the above code works properly.
İ think you are not logged in so you get error when you try to get Auth::user()-id
Add this contractor to your class i think it should work for you
public function __construct(){
$this->middleware('auth');
}

fetch data from database and display the values in database in laravel

I want to fetch values from database and display it in the view, but I didn't get a correct result.
This is my controller:
class HrRequestController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$hr_request = HrRequest::all();
return array(
'status' => 'success',
'pages' => $hr_request->toArray());
}
}
and this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class HrRequest extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'hr_request';
public $timestamps = false;
/**
* Fields.
*
* #var array
*/
protected $fillable = [
'profile_role_id', 'hr_id', 'vacancy', 'experience', 'job_description', 'status', 'viewed',
];
}
view name:view-requests.blade.php
I have no idea n how to do this in view. Can anyone help me?
Controller:
public function index()
{
$hr_request = HrRequest::all();
return view('view-requests')->with('hr_request', $hr_request);
}
View:
#foreach($hr_request as $row)
<tr>
<td>{{$row->profile_role_id}}</td>
<td>{{$row->vacancy}}</td>
<td>{{$row->experience}}</td>
<td>{{$row->job_description}}</td>
<td>
<button type="button" class="btn btn-primary">View</button>
<button type="button" class="btn btn-success">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</td>
</tr>
#endforeach
Route:
Route::get('/view-hr-requests', 'HrRequestController#index');
It's working

Doctrine - Auto insert rows association table

I have 3 tables : Profile - Permission - ProfilePermissionValue
Profile and Permission are classic entities, and ProfilePermissionValue is an association of a Profile.id, Permission.id, and an extra field representing the value of the permission for the profile.
When I add a Permission, I want a new row being inserted in ProfilePermissionValue for each Profile.
Same on reverse, when I add a new Profile, ... And same on delete by the way.
The question : Is there a way to do it with Doctrine (Symfony 3) functionalities, or I need to code it myself ?
I think you look at the permission <-> profile more strictly than you should. Basically in almost every ACL I worked with there was a assumption - when something is not allowed, it`s disallowed (or when something is not disallowed is allowed which is more dangerous). Which significantly reduce amount of data, you must save.
So when you create your entities like this
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
*/
class Permission
{
// id column
/**
* #ORM\Column(type="string")
* #var string
*/
private $name;
/**
* #return string
*/
public function getName()
{
return $this->name;
}
}
and
<?php
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity()
*/
class User
{
// id column
// name column
/**
* #ORM\ManyToMany(targetEntity=Permission::class)
* #ORM\JoinTable(name="allowed_permissions",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="permission_id", referencedColumnName="id")}
* )
* #var Permission[]|Collection
*/
private $allowedPermissions;
/**
* #return Permission[]
*/
public function getAllowedPermissions()
{
return $this->allowedPermissions->toArray();
}
}
you can simply implement your own class for interface AuthorizationCheckerInterface as
<?php
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class Authorizator implements AuthorizationCheckerInterface
{
/**
* #param string $name
* #param User $user
* #return bool
*/
public function isGranted($name, $user)
{
foreach ($user->getAllowedPermissions() as $permission) {
if ($permission->getName() === $name) {
return TRUE;
}
}
return FALSE;
}
}
without any needs of having deny permission in your database.

Laravel 5.3 - Data inserting issue in MySQL 5.7.1

While inserting data from Laravel 5.3 it doesn't show up in the MySQL 5.7.1 database. I was following a tutorial, the teacher was using Laravel 5.2 Is that an issue?
Any help would be appreciated.
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'body' => 'required'
));
// store in the database
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
// Session::flash('success', 'The blog post was successfully save!');
return redirect()->route('posts.show', $post->id);
}
Adding the whole code here...
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::all();
return view('posts.index')->withPosts($posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'body' => 'required'
));
// store in the database
$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect()->route('posts.show', $post->id);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->withPost($post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Make sure your $fillable array is populated.
<?php
namespace App;
class Post extends Model
{
protected $fillable = ['title', 'body'];
...
}