Good evening community.I'm executing a command on terminal, I want to access $per variable in my mail view and it is giving me an error that it can't recognize the $per variable.
This is the command code:
<?php
namespace App\Console\Commands;
use App\pamatrizinfoperio;
use App\Periodicidad;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class EnvAlert extends Command
{
//public $periodos;
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'Send:Alert';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send Emails';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$pers = Periodicidad::select('paperiodicidad.des','pamatrizinfoperio.des', 'pamatrizinfoperio.codpar')
->join('pamatrizinfoperio', 'pamatrizinfoperio.cod_paperiodicidad', '=', 'paperiodicidad.cod')
->where('pamatrizinfoperio.read_at', '=', 0)
->get();
$data = array('name' => "Alert" , );
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coop#gmail.com', 'ALERT');
$message ->to('coop#gmail.com')->subject('Alert');
});
return "The alert was send";
}
}
And this is the view:
<!DOCTYPE html>
<html>
<head>
<title>Message Send</title>
</head>
<body>
<ul class="list-group">
#foreach($pers as $per)
<li class="list-group-item">
{{$per->des}}
{{$per->des}}
</li>
#endforeach
#endforeach
</ul>
</body>
</html>
I have the same variable in other views, with the same query in the code and it works normally only that I declare them in the controller, but in this case I do not know why it does not work for me, I hope you can help me, any data you need I will provide. Sorry if my English is a little bad, I would appreciate a lot to help me in this, because as you will notice the function of the system so to speak, it is only to send emails informing about a job and the time to deliver it. Thanks in advance for your time.
You are passing variable named $data to the mail and you are accessing a different variable in the mail view
In you case, Your handle function should be like this
public function handle(){
$pers = Periodicidad::select('paperiodicidad.des','pamatrizinfoperio.des', 'pamatrizinfoperio.codpar')
->join('pamatrizinfoperio', 'pamatrizinfoperio.cod_paperiodicidad', '=', 'paperiodicidad.cod')
->where('pamatrizinfoperio.read_at', '=', 0)
->get();
$data = ['name' => 'Alert',
'pers' => $pers];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coop#gmail.com', 'ALERT');
$message ->to('coop#gmail.com')->subject('Alert');
});
return "The alert was send";
}
Then you will be able to access the $pers in your mail view,
I hope it helped you :)
Related
blade.php file that shows all Posts from my database
Im trying to add a search bar that will filter all these posts to prioritise according to title but i cant seem to get it working at all
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12 pt-2">
<div class="row">
<div class="col-8">
#if (Auth::user() && Auth::user()->is_admin)
<h1 class="display-one">Bloggy</h1><h2>Admin</h2>
#endif
</div>
<!-- Check to see if the user is a guest, if they are the Add post button is hidden -->
#if(!Auth::guest())
<div class="col-4">
Add Post
</div>
#endif
</div>
#if (Auth::user() && Auth::user()->is_admin)
<div class="col-4">
Manage Users
</div>
#endif
<!-- HERE -->
<form>
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
#forelse($posts as $post)
<ul>
<li>{{ ucfirst($post->title) }}</li>
<li>{{ ucfirst($post->created_at) }}</li>
</ul>
<p>
{{ $post->user->name }}
</p>
<p>
{{ $post->tag->name }}
</p>
#empty
<p class="text-warning">No blog Posts available</p>
#endforelse
</div>
</div>
</div>
#endsection
Here is my posts controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')
->paginate(20);
return view('posts/index', [
'posts'=> $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
*/
// References
// Jefferey Way. laracasts. Laravel 8 from scratch. laracasts.com. https://laracasts.com/series/laravel-8-from-scratch
public function store(Request $request)
{
$request->validate([
'tag_id' => 'required',
'title'=> 'required',
'body'=> 'required',
]);
$post = new Post;
//dd(Auth::user());
$post->user()->associate(Auth::user());
$post->title = $request->title;
$post->body = $request->body;
$post->tag_id = $request->tag_id;
$post->save();
return redirect()->route('posts.index')
->with('success', 'Post created succesfully');
}
/**
* Display the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('posts.show', [
'post'=> $post,
]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.edit', [
'post' => $post
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required'
]);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated succesfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Deleted Succesfully');
}
public function showPostsByUser(User $user)
{
$posts = Post::where('user_id', $user->id)->get();
return view('posts.userposts', compact('posts', 'user'));
}
// Search function here
public function search()
{
// Check for search input
if (request('search')) {
$posts = Post::where('title', 'like', '%' . request('search') . '%')->get();
} else {
$posts = Post::all();
}
return view('posts.show')->with('posts', $posts);
}
}
Here is my routes file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\CommentController;
use App\Http\Controllers\RegisterController;
use App\Http\Controllers\AdminController;
use App\Models\Tag;
use App\Model\Post;
use App\Model\Users;
/*
|--------------------------------------------------------------------------
| 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('/', [WelcomeController::class, 'index']);
Route::resource('/posts', PostController::class);
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
Route::post('posts/{post}/comments', [CommentController::class, 'store']);
Route::get('/register', [RegisterController::class, 'create'])->name('register.create')->middleware('guest');
Route::post('/register', [RegisterController::class, 'store'])->name('register.store')->middleware('guest');
Route::get('/login', [LoginController::class, 'login'])->name('login');
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
Route::post('/login', [LoginController::class, 'authenticate'])->name('authenticate');
Route::resource('/admin', AdminController::class)->middleware('admin');
// Route::get('/tags/{tag}', function(Tag $tag) {
// return view('posts/index', [
// 'posts'=>$tag->posts
// ]);
// });
Route::get('/posts/user/{user}', [PostController::class, 'showPostsByUser'])->name('posts.showPostsByUser');
I cant seem to get anything working when i search in the bar on the main page my url changes to
http://localhost/posts?search=postname
And then nothing happens
Any help would be appreciated thanks, still trying to learn Laravel
EDIT:
It just seems to stay on the same page just the url changes
So you have a couple options here. You can define a separate route for /posts/search, or you can hook into the existing /posts (index) Route:
Define a GET Route for this new Search URL:
routes/web.php:
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
PostsController.php:
public function search(Request $request) {
$postsQuery = Post::latest(); // `latest()` is shorthand for `orderBy('created_at', 'DESC');`
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
Lastly, update the <form> element for this Search function:
<form action="{{ route('search') }}">
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
Now, when you navigate to http://localhost/posts/search, you'll get 20 Post records, ordered by created_at.
If you navigate to http://localhost/posts/search?search=example, you'll get up to 20 Post records, but only those that include example in their title.
You'll notice how similar that is to the index() method; so you can merge them to make your code a bit more "DRY" (Don't Repeat Yourself):
PostsController.php
public function index(Request $request) {
$postsQuery = Post::latest();
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
You don't need Route::get('/posts/search', ...); anymore. Instead, if you navigate to http://localhost/posts, you'll get the latest 20 Post records. If you navigate to http://localhost/posts?search=example, you'll get up to 20 Post records, ordered by created_at, but only those that include example in the title.
I'm trying to cheek the user is online or offline in my chat blade. I make a realtime chat in Laravel using Pusher and it's working fine but I have a issue to show user online offline status. I make middleware LastUserActivity and also registerd a my middleware in kernel.php but I constantly get this error.
Call to undefined method stdClass::save()
middleware
<?PHP
namespace App\Http\Middleware;
use Closure;
use Auth;
use Cache;
use Carbon\Carbon;
class LastUserActivity
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check()){
$expiresAt = Carbon::now()->addMinutes(1);
Cache::put('user-is-online-'.Auth::user()->id, true, $expiresAt);
}
return $next($request);
}
}
User Model
<?PHP
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Cache;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'gender', 'dob', 'image', 'password', 'is_admin', 'mobile', 'service_id', 'country_id', 'city_id', 'piincode'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//check if User is online
public function isOnline()
{
return Cache::has('user-is-online-'. $this->id);
}
}
my blade file is
<ul class="users">
#foreach($users as $user)
<li class="user" id="{{ $user->id }}">
{{--will show unread count notification--}}
#if($user->unread)
<span class="pending">{{ $user->unread }}</span>
#endif
<div class="media">
<div class="media-left">
<img src="{{ URL::asset('storage/uploads/vendor/'.$user->image) }}" alt="" class="media-object">
</div>
<div class="media-body">
<p class="name">{{ $user->name }}</p>
<p class="email">{{ $user->email }}</p>
#if ($user->isOnline())
<li class="text-success">Online</li>
#else
<li class="text-muted">Offline</li>
#endif
</div>
</div>
</li>
#endforeach
</ul>
my controller file is
<?PHP
namespace App\Http\Controllers;
use App\Message;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Pusher\Pusher;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = DB::select("select users.id, users.name, users.image, users.email, count(is_read) as unread
from users LEFT JOIN messages ON users.id = messages.from and is_read = 0 and messages.to = " . Auth::id() . "
where users.id != " . Auth::id() . "
group by users.id, users.name, users.image, users.email");
return view('admin.chat', ['users' => $users]);
}
}
please help me. Thanks in advance
$users = DB::select("select users.id, users.name, users. ....
the $users will not hold a collection of user but a collection of std class ...
to hold a collection of users you should get the result using User Model ...
something like:
$users = User::selectRaw("users.id, users.name, users.image, users.email, count(is_read) as unread"
)->leftJoin('messages', 'users.id', 'messages.from')
->where('is_read', 0)->where('messages.to', Auth::id())
->where('users.id', '!=', Auth::id())
->groupBy(['users.id', 'users.name', 'users.image', 'users.email'])->get();
I want to send several emails, so that they are linked in a transition table, well all good, the problem is that when I use the command it only sends me an email and it is not repeated by each user as it should be because when using the foreach, I should send an email for each user that takes, at the same time review each query separately and if more than one user grabs me so I do not know why the command only sends me a single email. I hope you can help me and on the other hand I also want to use the email of the sis variable, but when using it within the 'mail' it tells me that said variable does not exist. Thanks for all beforehand.
my controller:
<?php
namespace App\Console\Commands;
use App\p;
use App\User;
use App\Pe;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
class Alertc extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'S:AC';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send works';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$hour= 14;
$minute= 0;
$second=0;
$year= date("Y");
$month= date("m");
$day=date("d");
$hourM=date("H");
$dayy= now();
$datelim=Carbon::Create($year,$month,$day,$hour,$minute,$second);
$datedif=Carbon::Create($year,$month,$day,$hourM,$minute,$second);
$dateen= $Datedif->addHour();
$intervalH= $dayy->diffInHours($datelim);
$intervalM= $dayy->diffInMinutes($dateen);
$systems = User::where('codarea','>',0)->get();
foreach ($systems as $system) {
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy)
->get();
$data = ['name' => "Alert" , 'periods' => $sis, 'Periodres' => $intervalH, 'Periodresm' => $intervalM,
'Hactual' => $dayy, 'Hlimit' => $dateend];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coopme#gmail.com', 'ALERT');
$message ->to('coopme#gmail.com')->subject('Alert');
});
return "La alert is finished";
}
}
}
my view:
<!DOCTYPE html>
<html>
<head>
<title>Message Sent</title>
</head>
<body>
<ul class="list-group">
Good morning the next works is:
#foreach($periods as $period)
<li class="list-group-item">
must send
<b>{{$period->description}}</b>
#if($Hactual<$Hlimit)
the limit is
{{$Periodres}} Hours and
{{$Periodresm}} Minutes.
#elseif($Hactual>$Hlimit)
is finished.
#endif
</li>
#endforeach
<b><h6>Always with you</h6></b>
</ul>
</body>
</html>
this is my controller when i want use the sis variable inside the mail:
namespace App\Console\Commands;
use App\p;
use App\User;
use App\Pe;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
class Alertc extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'S:AC';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send works';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$hour= 14;
$minute= 0;
$second=0;
$year= date("Y");
$month= date("m");
$day=date("d");
$hourM=date("H");
$dayy= now();
$datelim=Carbon::Create($year,$month,$day,$hour,$minute,$second);
$datedif=Carbon::Create($year,$month,$day,$hourM,$minute,$second);
$dateen= $Datedif->addHour();
$intervalH= $dayy->diffInHours($datelim);
$intervalM= $dayy->diffInMinutes($dateen);
$systems = User::where('codarea','>',0)->get();
foreach ($systems as $system) {
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy)
->get();
$data = ['name' => "Alert" , 'periods' => $sis, 'Periodres' => $intervalH, 'Periodresm' => $intervalM,
'Hactual' => $dayy, 'Hlimit' => $dateend];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coopme#gmail.com', 'ALERT');
$message ->to(sis->email)->subject('Alert');
});
return "La alert is finished";
}
}
}
Your query is:
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy
->get();
It returns a collection. You need to foreach $sis and make an email array or use a method like first(), last()...
Something like this:
$message ->to($sis->first()->email)->subject('Alert'); //To send to the first user of your query
You're missing the $ character in this section:
$message ->to(sis->email)->subject('Alert');
Must be:
$message ->to($sis->email)->subject('Alert');
I cannot access to the attribute "price" in my Mail class in Laravel. I´ve got an error
Undefined index: price (View: C:\laragon\www\hr-english\resources\views\external__emails\registered-course.blade.php)
I think the problem is the controller. I had to do a query to the database to check the price of the course, because in my registered_courses table I have a foreign key related to courses which return to me the title of the course and its price.
When I got from the query those data and send the variables to the blade, it appears the error shown at the top.
My controller
public function store(Request $request)
{
try {
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user();
$msg = $data;
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
RegisteredCourse::create($data);
Mail::to($email)->queue(new RegistCourse($msg, $email, $name, $price));
return redirect()->route('registeredCourse.index')
->with('sucess_message', 'Registered course was sucessfully added');
} catch(Exception $exception) {
return back()->withInput()
->withErrors(['unexpected_error' => 'Unexpected error occurred while trying to process your request.']);
}
}
My Mailable
class RegistCourse extends Mailable
{
use Queueable, SerializesModels;
public $subject = 'Registered Course';
public $msg;
public $email;
public $name;
public $price;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($msg, $email, $name, $price)
{
$this->msg = $msg;
$this->email = $email;
$this->name = $name;
$this->price = $price;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('external__emails.registered-course');
}
}
This is my blade template
<body>
<div class="container">
<div class="row">
<div>
<img src="{{asset('images/logo_leon.png')}}" alt="logo_leon" width="55" id="logo_login"><span style="color:gray">HOLYROOD ENGLISH SCHOOL</span>
</div>
<br>
<div>
<p>Thank you very much for your purchase, {{$name['name']}}. You have just registered in one of our courses.</p>
<p>
<table>
<tr>
<th>Name</th>
<th>Course</th>
<th>Date of purchase</th>
</tr>
<tr>
<td>{{$msg['course_id']}}</td>
<td>{{$price['price']}}</td>
</tr>
</table>
</p>
</p>
<p>See you in class. Surely we enjoy learning English.</p>
<p>If you have any questions, do not hesitate to contact us through any of our contact forms.</p>
<br>
<p>Equipo Holyrood English School</p>
</div>
</div>
</div>
</body>
</html>
In your code:
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user(); // Should be Auth::user()->name (if name exists)
$msg = $data;
// The get() method returns an array even if there is one row.
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
So, $price should be $price[0]->price in the view or use first() method instead of get(). So, the name should be the property of the user model, Auth::user() will result in an object.
pay attention to the '->with' function that I use to send the datas to the view.
YOUR MAILING CLASS:
class SuccessBooking extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $booking;
public $user;
public $pdf_path;
public $rideCode;
public function __construct($user, $booking, $pdf_path, $rideCode)
{
$this->booking = $booking;
$this->user = $user;
$this->pdf_path = $pdf_path;
$this->rideCode = $rideCode;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('noreply#coride.com', "Co Ride Receipt")
->view('email/successbookinginvoice')
->attach(public_path($this->pdf_path))
->with([
'user' => $this->user,
'code' => $this->rideCode,
'path' => public_path($this->pdf_path),
'booking' => $this->booking,
]
);
}
}
YOUR BLADE TEMPLATE
#section('content')
{{--below we access a particular item in the object user--}}
<h5>Dear {{$user->firstName}}, congratulations on your successful booking.</h5>
{{--below we just access code, it's not an object--}}
<h5>Dear {{$code}}, congratulations on your successful booking.</h5>
#endsection
i am unable to login in laravel 5 at admin side
my users table data in mysql is
username=admin Primary key
password=admin
is there any problem in my code if there then let me know please...
my code is following
Route.php
Route::group(array('prefix'=>'admin'),function(){
Route::filter('pattern: admin/*', 'auth');
Route::get('login', 'admin\AdminHomeController#showLogin');
Route::post('check','admin\AdminHomeController#checkLogin');
Route::get('adminlogout', 'admin\AdminHomeController#logout');
Route::get('dashboard', 'admin\AdminHomeController#showDashboard');
});
Users.php // my module
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
public static $auth_rules=[
'username'=>'required',
'password'=>'required'
];
/**
* The database table used by the model.
*
* #var string
*/
public $timestamps=false;
protected $table = 'users';
public $primaryKey = 'username';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['username', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function getAuthPassword()
{
return $this->password;
}
/**
* Automatically Hash the password when setting it
* #param string $password The password
*/
public function setPassword($password)
{
$this->password = Hash::make($password);
}
}
AdminHomeController.php
<?php namespace App\Http\Controllers\admin;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
class AdminHomeController extends Controller {
//
public function showLogin()
{
return view('admin.login');
}
public function checkLogin(Request $request)
{
$data=array(
'username'=>$request->get('username'),
'password'=>$request->get('password')
);
print_r($data);
if(Auth::attempt($data))
{
echo "ok";die;
return redirect::intended('admin/dashboard');
}
else
{
echo "not ok";die;
return redirect('admin/login');
}
}
public function logout()
{
Auth::logout();
return redirect('admin/login');
}
public function showDashboard()
{
return view('admin.dashboard');
}
}
I don't know what made you to use backslash (\) in your routes.php file.
In your checkLogin method, you are attempting to login, which I presume it does logs the admin in his dashboard provided the login credentials are correct.
You are using die; which will stop the execution of the script, hence, there is no redirection.
Also, you have not mentioned what is/are the error(s) that you get when you try login.
Change this code:
/**
* Automatically Hash the password when setting it
*
* #param string $password The password
*/
public function setPassword($password)
{
$this->password = Hash::make($password);
}
to this:
/**
* Automatically Hash the password when inserting
*
* #param string $password The password
*/
public function setPasswordAttribute($password)
{
// You need to import the Hash Facade in
// to hash your password.
$this->password = Hash::make($password);
// or use this if you do not want to import
// the Hash Facade.
$this->password = bcrypt($password);
}
Whenever you want to set the attribute to its corresponding / respective value, you should prefix the attribute with the word set and suffix the same attribute with the word Attribute. (Notice capital A in Attribute). So, in your code, it should be setPasswordAttribute. Laravel will then save the value that you want it to save in the database table.
But just to get you going, this is how I do it:
routes.php
Route::get('/admin', 'UsersController#getAdminLogin');
Route::get('/admin/dashboard', 'UsersController#dashboard');
Route::post('/admin', 'UsersController#postAdminLogin');
admin_login.blade.php
{!! Form::open(['url' => '/admin']) !!}
<div class="form-group">
{!! Form::label('email', 'Email Id:') !!}
{!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
</div>
{!! Form::close() !!}
dashboard.blade.php
<h4 class="text-center">
Welcome Admin, {{ Auth::user()->username }}
</h4>
UsersController.php
/**
* Display the admin login form if not logged in,
* else redirect him/her to the admin dashboard.
*
*/
public function getAdminLogin()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return redirect('/admin/dashboard');
}
return view('admin_login');
}
/**
* Process the login form submitted, check for the
* admin credentials in the users table. If match found,
* redirect him/her to the admin dashboard, else, display
* the error message.
*
*/
public function postAdminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email,role,admin',
'password' => 'required'
]);
$credentials = $request->only( 'email', 'password' );
if(Auth::attempt($credentials))
{
return redirect('/admin/dashboard');
}
else
{
// Your logic of invalid credentials.
return 'Invalid Credentials';
}
}
/**
* Display the dashboard to the admin if logged in, else,
* redirect him/her to the admin login form.
*
*/
public function dashboard()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return view('admin.dashboard');
}
return redirect('/admin');
}
Visit this link for more learning on routes.
If you are using following function to set password while registering/adding admin user,
change
Hash::make($password)
to
bcrypt($password)