I'm having a problem with my Auth. So, I'm doing login but not using User models. I made my own models called Karyawan.
The error is:
Method Illuminate\Auth\SessionGuard::karyawan does not exist.
This is the public function on my controller:
public function admin()
{
return view('admin', [
"title" => "Admin",
"karyawan" => Karyawan::all()
]);
}
This is the auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Karyawan::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
my Karyawan models:
namespace App\Models;
use App\Models\Cuti;
use App\Models\Role;
use App\Models\Divisi;
use App\Models\Jabatan;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Karyawan extends Authenticatable
{
use HasFactory;
protected $guarded = ['karyawan_id'];
protected $table = 'karyawans';
public function scopeSearch($query, array $searchs) {
$query->when($searchs['search'] ?? false, function($query, $search) {
return $query->where('nama', 'like', '%' . $search . '%')
->orWhere('divisi_id', 'like', '%' . $search . '%')
->orWhere('jabatan_id', 'like', '%' . $search . '%')
->orWhere('agama', 'like', '%' . $search . '%')
->orWhere('nik', 'like', '%' . $search . '%');
});
}
public function role_id()
{
return $this->belongsTo(Role::class);
}
public function divisi()
{
return $this->belongsTo(Divisi::class);
}
public function jabatan()
{
return $this->belongsTo(Jabatan::class);
}
public function cuti()
{
return $this->hasMany(Cuti::class);
}
}
and this is the view I want to display:
<div class="dropdown">
<a href="#" class="d-flex align-items-center link-dark text-decoration-none dropdown-toggle" id="dropdownUser2" data-bs-toggle="dropdown" aria-expanded="false">
<img src="/images/avatar/avatar-2.png" alt="" width="32" height="40" class="rounded-circle me-2">
<strong>{{ auth()->karyawan()->nama }}</strong>
</a>
<ul class="dropdown-menu text-small shadow" aria-labelledby="dropdownUser2">
<li>
<form action="">
<button type="submit" class="dropdown-item">Logout</button>
</li>
</ul>
</div>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2" style="position:absolute margin: auto auto"><p></p>Profil Pengguna</h1>
</div>
<center>
<img src="/images/avatar/avatar-2.png" style="width: 200px">
<p><h1>Selamat Datang, {{ auth()->karyawan()->nama }}</h1> </p>
<p> Divisi: {{ auth()->divisi()->nama_divisi }}</p>
<p> Jabatan: {{ auth()->jabatan()->nama_jabatan }}</p>
<p> Role: {{ auth()->role()->nama_role }}</p>
<p> Sisa cuti Anda: {{ auth()->karyawan()->sisa_cuti }}</p>
</center>
</div>
</main>
PS: The login auth is successful, not failed. the only problem is it can't display who is the user doing the login.
Related
im new to laravel and im trying to create login function with multiple guards. However when i insert the correct credentials in the form, it does not authenticate properly. I cant seem to find the problem with my login controller, any ideas?
This is my AdminLoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function showLoginForm()
{
return view('auth.admin-login');
}
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'admin_email ' => 'required|email',
'password' => 'required|min:8'
]);
//attempt to log the user in
if( Auth::guard('admin')->attempt(['admin_email'=>$request->admin_email, 'admin_password'=>$request->admin_password], $request->remember))
{
//if successful then send to their location
return redirect()->route('admin.dashboard');
}
//if fail redirect back to the login with the data
return redirect()->back()->withInput($request->only('admin_email','remember'));
}
}
This one is my form
#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">{{ __('Admin-Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.login.submit') }}">
#csrf
<div class="row mb-3">
<label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>
<div class="col-md-6">
<input id="admin_email" type="email" class="form-control #error('admin_email') is-invalid #enderror" name="admin_email" value="{{ old('admin_email') }}" required autocomplete="admin_email" autofocus>
#error('admin_email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="admin_password" type="password" class="form-control #error('admin_password') is-invalid #enderror" name="admin_password" required autocomplete="current-admin_password">
#error('admin_password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-3">
<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="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
This one is the Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $guard = 'admin';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'admin_email',
'admin_password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'admin_password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Edited: This is my route
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::prefix('admin')->group(function (){
Route::get('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'showLoginForm'])->name('admin.login');
Route::post('/login', [App\Http\Controllers\Auth\AdminLoginController::class, 'login'])->name('admin.login.submit');
Route::get('/', [App\Http\Controllers\adminController::class, 'index'])->name('home')->name('admin.dashboard');
});
my dd($request)
Illuminate\Http\Request {#43 ▼
#json: null
#convertedFiles: null
#userResolver: Closure($guard = null) {#260 ▶}
#routeResolver: Closure() {#268 ▶}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#45 ▶}
+request: Symfony\Component\HttpFoundation\InputBag {#44 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#51 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#47 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#48 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#46 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#49 ▶}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/admin/login"
#requestUri: "/admin/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\Store {#300 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
This is my config/auth file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'resident' => [
'driver' => 'session',
'provider' => 'residents',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'residents' => [
'driver' => 'eloquent',
'model' => App\Models\Resident::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'residents' => [
'provider' => 'residents',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admin' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
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
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
I can upload a picture, but when I try to update it, then there is no error. The file name changes in the database to the name of the new picture. And in the public folder the picture remains old and does not appear new.
I use: Intervention Image
What I did not understand, help please.
Controller: UploadController
use Illuminate\Http\Request;
use App\Post;
use Image;
use Storage;
use Faker\Provider\File;
public function update (Request $request, $id)
{
//validate
$this->validate($request, [
'title' => 'required|max:255',
'author' => 'required',
'text' => 'required',
'desc' => 'required',
'image' => 'required',
]);
$posts = Post::find($id);
$posts->title = $request->input('title');
$posts->author = $request->input('author');
$posts->text = $request->input('text');
$posts->desc = $request->input('desc');
$posts->image = $request->input('image');
//update image
if ($request->hasFile('image'))
{
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/'. $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $posts->image;
//update db
$posts->image = $filename;
//delete old image
Storage::delete($oldFilename);
}
$posts->save();
return redirect('/');
}
View: edit.blade.php
<div class="container">
<form method="POST" action="{{ route('goUpdate', [$posts->id]) }}">
{{ csrf_field() }}
{!! method_field('patch') !!}
#if($posts)
<div class="form-group">
<br>
<label>title</label>
<input name="title" type="text" class="form-control" value="{{ $posts->title }}">
</div>
<div class="form-group">
<label>author</label>
<input name="author" type="text" class="form-control" value="{{ $posts->author }}">
</div>
<div class="form-group">
<label>text</label>
<textarea name="text" class="form-control" rows="7">{{ $posts->text }}</textarea>
</div>
<div class="form-group">
<label>desc</label>
<textarea name="desc" class="form-control" rows="5">{{ $posts->desc }}</textarea>
</div>
<div class="form-group">
<label>image</label>
<input type="file" name="image" class="form-control-file" value="" >
</div>
<div>
<input name="submit" type="submit" class="btn btn-primary" value="update"/>
back
</div>
#endif
</form>
<br>
filesystems.php
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('images/'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
],
Try using this
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('events/' . $filename);
Image::make($image->getRealPath())->resize(300, 300)->save($path);
$event->image = 'events/' . $filename;
Hope this can help you
I'm using Laravel 5.2 and I'm trying to get the error message to show when I attempt to login with the wrong username and password combination, so when I do that I don't get an error message showing. I'm not sure where I'm going wrong.
My controler
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
class HomeController extends Controller
{
public function login(Request $request)
{
if(Auth::attempt(array('name' => Input::get('name'), 'password' => Input::get('password'))))
{
return redirect()->route('dashboard');
}else{
return redirect()->route('home')
->with('message', 'Your username and password combination is wrong')
->withInput();
}
}
}
my index.blade.php
#if ($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
#endif
<div class="form-wrapper">
<div class="login-header">
<h1>Login</h1>
</div>
<div class="form_input">
{{ Form::open(array('url' => 'admin/')) }}
<div class="form_group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', '' , array("class" => "form-control")) }}
</div>
<div class="form_group password-section">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array("class" => "form-control")) }}
</div>
<div class="form_group submit_button">
{{ Form::submit('Submit', array("class" =>"btn btn-info submit", "role" => "button")) }}
</div>
{{ Form::close() }}
</div>
</div>
My routes.php
Route::group(['middleware' => 'web'], function()
{
Route::get('admin/', [
'uses' => 'HomeController#index',
'as' => 'home'
]);
Route::post('/signin', [
'uses' => 'HomeController#login',
'as' => 'Login'
]);
});
use Route::group(['middleware' => 'auth'], function() in routes