Laravel 5.2 login issue - laravel

Strange issue, when I use the default register route, and I create a user, I can enter inside my app, everything ok. But if I use my CRUD, or the MySQL command for create the user, I can't login.
These credentials do not match our records. (sorry for bad english, I attach the image)
Andrea and Raffaello can login (create with register default route)
Marino can't (generate with my CRUD function) but appear 3 identical records..
routes.php :
Route::group(['middleware' => ['web']], function () {
Route::resource('dash/reports', 'Dash\\ReportsController');
});
/* ruote for Admin */
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/categories', 'Dash\\CategoriesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/roles', 'Dash\\RolesController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/permissions', 'Dash\\PermissionsController');
});
Route::group(['middleware' => ['role:admin']], function () {
Route::resource('dash/users', 'Dash\\UsersController');
});
/* another routes */
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/', function () {return view('welcome');});
Controller (custom CRUD operation)
<?php
namespace App\Http\Controllers\Dash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Report;
use App\Category;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Session;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UsersController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Display a listing of the resource.
*
* #return void
*/
public function index()
{
$users = User::paginate(15);
return view('dash.users.index', compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return void
*/
public function create()
{
return view('dash.users.create');
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
return redirect('dash/users');
}
/**
* Display the specified resource.
*
* #param int $id
*
* #return void
*/
public function show($id)
{
$user = User::findOrFail($id);
return view('dash.users.show', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
*
* #return void
*/
public function edit($id)
{
$user = User::findOrFail($id);
return view('dash.users.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
*
* #return void
*/
public function update($id, Request $request)
{
$this->validate($request, ['email' => 'required', 'name' => 'required', 'password' => 'required', 'surname' => 'required', ]);
$user = User::findOrFail($id);
$user->update($request->all());
Session::flash('flash_message', 'User updated!');
return redirect('dash/users');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
*
* #return void
*/
public function destroy($id)
{
User::destroy($id);
Session::flash('flash_message', 'User deleted!');
return redirect('dash/users');
}
}
view:
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Create New User</h1>
<hr/>
{!! Form::open(['url' => '/dash/users', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('email') ? 'has-error' : ''}}">
{!! Form::label('email', trans('users.email'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('email', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('email', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
{!! Form::label('name', trans('users.name'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('name', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('name', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('password') ? 'has-error' : ''}}">
{!! Form::label('password', trans('users.password'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('password', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('password', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('surname') ? 'has-error' : ''}}">
{!! Form::label('surname', trans('users.surname'), ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('surname', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('surname', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#if ($errors->any())
<ul class="alert alert-danger">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
</div>
#endsection
also my custon postLogin() in AuthController for try to overlap default postLogin() - but not working
public function postLogin(LoginRequest $request)
{
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')]))
{
return redirect('/dash-board');
}
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Riprovare?',
]);
}

there is it
you need to specify the data you get from $request
you are storing password not correctly
change this :
$user = new User($request->all());
$user->password = bcrypt($request);
$user->save();
to this :
$user = new User($request->all());
$user->password = bcrypt($request->pwInputName);
$user->save();
pwInputName : is the password input name in your view
the issue was that you bcrypt all of $request

Related

Laravel - 403 redirect. Redirect is correct working for tags and category sections but not for users

I'm trying to set the post admin section. The mission for that section is to show all articles that belong to logged user. The way I'm doing for tags and categories is working correct (tags and categories doesn't need to be filtered for any user). The post page works correctly show the owned post for logged user, but the problem is that the user can't edit or show any post and trying to store a new post redirects to 403 page. I'm confuse by the error and I don't have any solution. I appreciate some help.
PostModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'user_id', 'category_id', 'name', 'slug', 'excerpt', 'body', 'status', 'file'
];
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
}
PostController
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\PostStoreRequest;
use App\Http\Requests\PostUpdateRequest;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$posts = Post::orderBy('id', 'DESC')
->where('user_id', auth()->user()->id)
->paginate();
return view('admin.posts.index', compact('posts'));
}
public function create()
{
$categories = Category::orderBy('name', 'ASC')->pluck('name', 'id');
$tags = Tag::orderBy('name', 'ASC')->get();
return view('admin.posts.create', compact('categories', 'tags'));
}
public function store(PostStoreRequest $request)
{
$post = Post::create($request->all());
$this->authorize('pass', $post);
//IMAGE
if($request->file('image')){
$path = Storage::disk('public')->put('image', $request->file('image'));
$post->fill(['file' => asset($path)])->save();
}
//TAGS
$post->tags()->attach($request->get('tags'));
return redirect()->route('posts.edit', $post->id)->with('info', 'Success');
}
public function show($id)
{
$post = Post::find($id);
$this->authorize('pass', $post);
return view('admin.posts.show', compact('post'));
}
public function edit($id)
{
$categories = Category::orderBy('name', 'ASC')->pluck('name', 'id');
$tags = Tag::orderBy('name', 'ASC')->get();
$post = Post::find($id);
$this->authorize('pass', $post);
return view('admin.posts.edit', compact('post', 'categories', 'tags'));
}
public function update(PostUpdateRequest $request, $id)
{
$post = Post::find($id);
$this->authorize('pass', $post);
$post->fill($request->all())->save();
//IMAGE
if($request->file('image')){
$path = Storage::disk('public')->put('image', $request->file('image'));
$post->fill(['file' => asset($path)])->save();
}
//TAGS
$post->tags()->sync($request->get('tags'));
return redirect()->route('posts.edit', $post->id)->with('info', 'Success');
}
public function destroy($id)
{
$post = Post::find($id)->delete();
$this->authorize('pass', $post);
return back()->with('info', 'Deleted');
}
}
PostUpdateRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostUpdateRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'name' => 'required',
'slug' => 'required|unique:posts,slug,' . $this->post,
'user_id' => 'required|integer',
'category_id' => 'required|integer',
'tags' => 'required|array',
'body' => 'required',
'status' => 'required|in:DRAFT,PUBLISHED',
];
if($this->get('image'))
$rules = array_merge($rules, ['image' => 'mimes:jpg,jpeg,png']);
return $rules;
}
}
PostStoreRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostStoreRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'name' => 'required',
'slug' => 'required|unique:posts,slug',
'user_id' => 'required|integer',
'category_id' => 'required|integer',
'tags' => 'required|array',
'body' => 'required',
'status' => 'required|in:DRAFT,PUBLISHED',
];
if($this->get('image'))
$rules = array_merge($rules, ['image' => 'mimes:jpg,jpeg,png']);
return $rules;
}
}
And for example, the post.edit
#extends('admin.admin')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="card">
<div class="card-header">
{{ __('Editar artículo') }}
</div>
<div class="card-body">
{!! Form::model($post, ['route' => ['posts.update', $post->id], 'method' => 'PUT']) !!}
#include('admin.posts.partials.form')
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
And finally the form
<div class="form-group">
{{ Form::hidden('user_id', auth()->user()->id) }}
</div>
<div class="form-group">
{{ Form::label('category_id', 'Category') }}
{{ Form::select('category_id', $categories, null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{ Form::label('name', 'Tag name') }}
{{ Form::text('name', null, ['class' => 'form-control', 'id' => 'name']) }}
</div>
<div class="form-group">
{{ Form::label('slug', 'URL friendly') }}
{{ Form::text('slug', null, ['class' => 'form-control', 'id' => 'slug']) }}
</div>
<div class="form-group">
{{ Form::label('image', 'Image') }}
{{ Form::file('image') }}
</div>
<div class="form-group">
{{ Form::label('slug', 'State') }}
<label>
{{ Form::radio('status', 'PUBLISHED') }} Published
</label>
<label>
{{ Form::radio('status', 'DRAFT') }} Draft
</label>
</div>
<div class="form-group">
{{ Form::label('tags', 'Tags') }}
<div>
#foreach($tags as $tag)
<label>
{{ Form::checkbox('tags[]', $tag->id) }} {{ $tag->name }}
</label>
#endforeach
</div>
</div>
<div class="form-group">
{{ Form::label('excerpt', 'Excerpt') }}
{{ Form::textarea('excerpt', null, ['class' => 'form-control', 'rows' => '2']) }}
</div>
<div class="form-group">
{{ Form::label('body', 'Description') }}
{{ Form::textarea('body', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
{{ Form::submit('Guardar', ['class' => 'btn btn-sm btn-primary']) }}
</div>
#section('scripts')
<script src="{{ asset('components/stringToSlug/jquery.stringToSlug.min.js') }}"></script>
<script>
$(document).ready(function(){
$("#name, #slug").stringToSlug({
callback: function(text){
$('#slug').val(text);
}
});
});
</script>
#endsection
Sorry for the extension but it was necessary to explain the problem.
The authorize() method in controller method looks for a corresponding policy. If Laravel can't find the corresponding policy it throws unauthenticated exception.
So in this case $this->authorize('pass', $post), expects to find a PostPolicy class, otherwise it will throw unauthorized exception which is converted to 403 redirect by middleware.
Read more about Policies https://laravel.com/docs/8.x/authorization#creating-policies.
Note: When using FormRequest to handle validation, authorization can be done in FormRequest and there's not need to duplicate authorization in controller method

How to Redirect a new user to the edit profile page

I am having a problem here. When a new user register I want to redirect him/her to the edit profile page... how do I change the login controller to redirect to that page?
here is my RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/profiles/'.$user->id.'/edit';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'type' => ['required'],
'name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phone' => ['required', 'string', 'max:15', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'type' => $data['type'],
'password' => Hash::make($data['password']),
]);
if($data['type'] == 'Learner'){
$user->attachRole('learner');
return $user;
}
elseif($data['type'] == 'Guardian'){
$user->attachRole('guardian');
return $user;
}
elseif($data['type'] == 'Teacher'){
$user->attachRole('teacher');
return $user;
}
}
}
edit.blade.php
#extends('layouts.admin')
#section('main-content')
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">{{ $user->name }} {{$user->last_name}}</h1>
<hr/>
#if (session('message'))
<div class="alert alert-success border-left-success alert-dismissible fade show" role="alert">
{{ session('message') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<form method="POST" action="{{ route('profiles.update', $user->id) }}">
#csrf
#method('PATCH')
<div class="row">
<div class="col-md-9">
<div class="card shadow mb-4 px-4 pb-4">
<div class="card-header py-3 px-0">
<h6 class="m-0 font-weight-bold text-primary">User Information</h6>
</div>
#if(Auth::user()->hasRole(['superadministrator', 'administrator']))
<div class="row my-2">
<div class="col-md-2 font-weight-bold pt-2">Role:</div>
<div class="col-md-10">
<div class="form-group">
<select id="role" name="role" class="form-control #error('role') is-invalid #enderror" value="{{ old('role') }}">
<option value="">Choose user role...</option>
#foreach($roles as $role)
<option value="{{ $role->display_name }}" {{ $user->hasRole($role->name) ? 'selected' : '' }}>{{ $role->display_name }}</option>
#endforeach
</select>
#error('role')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
</div>
. . . . .
The user must come to this page after registration not to the home directory... please help
In create method change the redirect variable like this:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'phone' => $data['phone'],
'type' => $data['type'],
'password' => Hash::make($data['password']),
]);
// change redirect variable
$this->redirectTo = '/profiles/'.$user->id.'/edit';
if($data['type'] == 'Learner'){
$user->attachRole('learner');
return $user;
}
elseif($data['type'] == 'Guardian'){
$user->attachRole('guardian');
return $user;
}
elseif($data['type'] == 'Teacher'){
$user->attachRole('teacher');
return $user;
}
}
A solution :
Create a migration how add $table->boolean('profil_edited')->default(0);
Update your model to add this field on the $fillable array
Check this value :
when users login, and redirect the user to the profile page
or in a middleware

How to add action columns in yajra datatables laravel

im stuck adding column actions for edit and delete button with yajra datatables, im using DataTables Service because im wanna add export button too, here is my my datatables code :
public function dataTable($query)
{
return datatables()
->eloquent($query);
}
/**
* Get query source of dataTable.
*
* #param \App\InfoDataTable $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(InfoDataTable $model)
{
// return $model->newQuery();
$data = DataInfo::select('data-info.*');
return $this->applyScopes($data);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction()
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'print'],
]);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('employee_no'),
Column::make('name'),
Column::make('address'),
Column::make('birthplace'),
Column::make('birthdate'),
Column::make('age'),
Column::make('occupation'),
Column::make('status'),
Column::make('gender'),
Column::make('startdate'),
];
}
and here is my code in my controller for rendering the table
public function index(InfoDataTable $dataTable)
{
$User = User::where('id', Auth::id())->first();
if($User->role == 'superadmin'){
return $dataTable->render('superadmin.index');
} else {
return $dataTable->render('admin.index');
}
}
and my blade looks like this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
<div class="card-body">
<div class="table-responsive">
<div class="panel panel-default">
{{(!! $dataTable->table() !!)}}
</div>
</div>
</div>
</div>
</div>
</div>
#stop
#push('scripts')
{!! $dataTable->scripts() !!}
#endpush
my current view looks like this
any suggestions? sorry for my broken english, tried many tutorial but can't find the correct one
Actions column is default for yajra datatables. So I found how to remove it: https://yajrabox.com/docs/laravel-datatables/6.0/remove-column (I have never tried this)
public function dataTable($query)
{
return datatables()
->eloquent($query)
->removeColumn('action');
}
If you want to edit actions column, try my code:
public function dataTable($query)
{
$dataTable = new EloquentDataTable($query);
return $dataTable->addColumn('action', 'folderNameInViewfolder.datatables_actions');
}
This is what in datatables_actions (full name: datatables_actions.blade.php)
{!! Form::open(['route' => ['routename.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
<a href="{{ route('routename.show', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-eye-open"></i>
</a>
<a href="{{ route('routename.edit', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-edit"></i>
</a>
{!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
'type' => 'submit',
'class' => 'btn btn-danger btn-xs',
'onclick' => "return confirm('Are you sure?')"
]) !!}
</div>
{!! Form::close() !!}
My code is different from yours, so I will show my code:
Datatables code:
public function dataTable($query)
{
$dataTable = new EloquentDataTable($query);
return $dataTable->addColumn('action', 'cachthuclamviecs.datatables_actions');
}
/**
* Get query source of dataTable.
*
* #param \App\Models\Cachthuclamviec $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(Cachthuclamviec $model)
{
return $model->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '120px', 'printable' => false])
->parameters([
'dom' => 'Bfrtip',
'stateSave' => true,
'order' => [[0, 'desc']],
'buttons' => [
['extend' => 'create', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-plus"></i> Thêm</span>'],
['extend' => 'export', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-download"></i> Xuất <span class="caret"></span></span>'],
['extend' => 'print', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-print"></i> In</span>'],
['extend' => 'reset', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-undo"></i> Cài lại</span>'],
['extend' => 'reload', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-refresh"></i> Tải lại</span>'],
],
]);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
'cachthuclamviec'
];
}
Controller code:
public function index(CachthuclamviecDataTable $cachthuclamviecDataTable)
{
return $cachthuclamviecDataTable->render('cachthuclamviecs.index');
}
Blade code:
#section('css')
#include('layouts.datatables_css')
#endsection
{!! $dataTable->table(['width' => '100%', 'class' => 'table table-striped table-bordered']) !!}
#push('scripts')
#include('layouts.datatables_js')
{!! $dataTable->scripts() !!}
#endpush
datatables_actions blade code:
{!! Form::open(['route' => ['cachthuclamviecs.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
<a href="{{ route('cachthuclamviecs.show', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-eye-open"></i>
</a>
<a href="{{ route('cachthuclamviecs.edit', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-edit"></i>
</a>
{!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
'type' => 'submit',
'class' => 'btn btn-danger btn-xs',
'onclick' => "return confirm('Are you sure?')"
]) !!}
</div>
{!! Form::close() !!}
Put file datatables_actions here: datatables_actions:
Code maybe have differences because of Boostrap, jQuery,... version

storing data with name of author - laravel 5.2

I have hasMany relation to my model user and reports.
I want to set author name for the reports. (Like a blog-post author)
my model User:
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
model Report
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
and my controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
I'm able to set in in phpmyadmin, but how can i set it with my controller?
edit: my view:
{!! Form::open(['url' => '/dash/reports', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Servizio', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('title', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('date', 'Data lavorativa', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-2">
{!! Form::selectRange('day', 1, 31, null, ['class' => 'form-control']) !!}
{!! $errors->first('day', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::selectMonth('month', null, ['class' => 'form-control']) !!}
{!! $errors->first('month', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::select('year', array('2016' => '2016', '2015' => '2015'), null, ['class' => 'form-control']) !!}
{!! $errors->first('year', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : ''}}">
{!! Form::label('category_id', 'Cliente', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
Very easy. Replace Report::create... with this.
$user = Auth::user();
$report = new Report($request->all());
$report->author()->associate($user);
$report->save();
Make sure you use Auth; up at the top.
This uses the Auth object to get the current user,
Builds a new Report using the $request data without saving,
Tells the report we're associating $user as the author for the model,
Saves the report with the authorship information.
solution:
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

Laravel 5 MethodNotAllowedHttpException issues

I am trying to make a simple CRUD for Clients. At the moment I can view clients and get to the edit page. However, if I try to update or create a client, I get a MethodNotAllowedHttpException.
My routes look like the following
Route::model('clients', 'Client');
Route::bind('clients', function($value, $route) {
return App\Client::whereSlug($value)->first();
});
Route::resource('clients', 'ClientsController');
My controller is like so
<?php
namespace App\Http\Controllers;
use App\Client;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Redirect;
use Illuminate\Http\Request;
class ClientsController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$clients = Client::all();
return view('clients.index', compact('clients'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('clients.create');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
Client::create( $input );
return Redirect::route('clients.index')->with('message', 'Client created');
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Client $client
* #return Response
*/
public function edit(Client $client)
{
return view('clients.edit', compact('client'));
}
/**
* Update the specified resource in storage.
*
* #param \App\Client $client
* #return Response
*/
public function update(Client $client)
{
$input = array_except(Input::all(), '_method');
$client->update($input);
return Redirect::route('clients.index', $client->slug)->with('message', 'Client updated.');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Client $client
* #return Response
*/
public function destroy(Client $client)
{
$client->delete();
return Redirect::route('clients.index')->with('message', 'Client deleted.');
}
}
I then have a form partial like so
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('clientName', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('contactEmail', 'Contact Email:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('contactEmail', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('slug', 'Slug:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('slug', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::submit($submit_text, ['class'=>'btn btn-default']) !!}
</div>
And my edit.blade.php is like so
<h2>Edit Client</h2>
{!! Form::model($client, ['class'=>'form-horizontal'], ['method' => 'PATCH', 'route' => ['clients.update', $client->slug]]) !!}
#include('clients/partials/_form', ['submit_text' => 'Edit Client'])
{!! Form::close() !!}
I have researched this error and a lot of people refer to javascript, but I am not using any javascript at the moment.
Why would I be getting this error? As I say, I get it when I try to create a client as well.
Thanks
As an update, if I remove the form partial and add this to ed.it.blade.php instead, it seems to work
{!! Form::model($client, [
'method' => 'PATCH',
'route' => ['clients.update', $client->slug]
]) !!}
<div class="form-group">
{!! Form::label('clientName', 'Client Name:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('clientName', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('contactEmail', 'Contact Email:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('contactEmail', null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('slug', 'Slug:', array('class' => 'col-sm-5 control-label blue')) !!}
<div class="col-sm-7">
{!! Form::text('slug', null, array('class' => 'form-control')) !!}
</div>
</div>
{!! Form::submit('Update Client', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Why is that?

Resources