I keep getting status 500 when 200 is expected. These are the files:
ExampleTest.php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="MAIL_DRIVER" value="array"/>
</php>
</phpunit>
This is the result returned
PHPUnit 7.4.0 by Sebastian Bergmann and contributors.
.F 2 / 2 (100%)
Time: 1.86 seconds, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\ExampleTest::testBasicTest
Expected status code 200 but received 500.
Failed asserting that false is true.
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:133
/var/www/html/tests/Feature/ExampleTest.php:19
FAILURES!
Tests: 2, Assertions: 2, Failures: 1.
This is the Laravel log file
[2018-10-15 20:56:09] testing.ERROR: Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) {"exception":"[object] (ErrorException(code: 0): Call to a member function load() on null (View: /var/www/html/resources/views/app.blade.php) at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46, Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function load() on null at /var/www/html/app/Ezybyz/Configuration/ProvidesScriptVariables.php:46)
app.blade.php
#php
$config = array_merge(
Ezybyz::scriptVariables(), [
// Add key and value here if you want to added to initial state
]
)
#endphp
#extends('layouts.main')
#push('meta')
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<meta name="csrf-token" content="{{ csrf_token() }}">
{{-- Fix for chunk error in Webpack and Vue-Router --}}
<base href="/" />
#endpush
#push('favicon')
<link rel="shortcut icon" href="{{ asset('favicon.ico?v=2') }}" type="image/x-icon" />
#endpush
#push('css')
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
#endpush
#push('header_js')
{{-- EzyByz initial state provider --}}
<script>
window.App = #json($config)
</script>
{{-- Add whitelisted routes for making API calls --}}
#routes
#endpush
#push('title')
<title>{{ config('app.name') }} </title>
#endpush
#section('content')
<div id="app" v-cloak>
<app />
</div>
#endsection
#push('footer_js')
#if(config('echo.realtime'))
{{-- Load socket.io --}}
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js" defer></script>
#endif
<script src="{{ mix('js/manifest.js') }}" defer></script>
<script src="{{ mix('js/vendor.js') }}" defer></script>
<script src="{{ mix('js/app.js') }}" defer></script>
#endpush
ProvidesScriptVariables.php
<?php
namespace App\Ezybyz\Configuration;
use App\Ezybyz\Ezybyz;
use Illuminate\Support\Facades\Auth;
use App\Ezybyz\Contracts\InitialFrontendState;
trait ProvidesScriptVariables
{
/**
* Get the default JavaScript variables for Spark.
*
* #return array
*/
public static function scriptVariables()
{
return [
'csrfToken' => csrf_token(),
'env' => config('app.env'),
'api_endpoint' => config('ezybyz.app.api'),
'sponsor' => self::getSponsor(),
];
}
protected static function getState()
{
return Ezybyz::call(InitialFrontendState::class . '#forUser', [Auth::user()]);
}
protected static function getSponsor()
{
if ($link = request()->referrallink) {
$user = Ezybyz::user()->find($link->user_id);
return [
'user_id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'profile' => $user->profile,
];
}
// We Will Return a Default Sponsor
else {
$user = Ezybyz::user()->first()->load('profile');
return [
'user_id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'profile' => $user->profile,
];
}
}
}
Any help is greatly appreciated.
Try to use RefreshDatabase trait in the test class:
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
use RefreshDatabase;
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
add $this->withoutExceptionHandling(); before $response = $this->get('/'); to get more information about the error.
One possible cause of this error message is, you don't have the openssl
php
extension enabled.
just edit your class to return true
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$this->assertTrue(true);
}
}
then run test in your command
vendor/bin/phpunit
Do check with your routes. Check if you have provided 'name' to your base route.
eg:
In routes/web.php, Do the following:
Route::get('home','BlogController#home')->name('home');
Now go to the test case and do replace the following code:
$response = $this->get('home');
Let me know if it works for you.
Related
I am trying to send email by html code.
I would like to include image and data on the blade template, but can't render the view.
current code:
MailTemplate.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MailTemplate extends Mailable
{
use Queueable, SerializesModels;
public $subject = null;
public $template;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($subject, $template, $data)
{
//
$this->subject = $subject;
$this->template = $template;
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->template = '<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>';
return $this->subject( $this->subject)->view('emails.EmailTemplate');
}
}
EmailTemplate.blade.php
<html>
<body>
{!! $template !!}
</body>
</html>
result
current:
<html>
<body>
<div><img src="{{ $message->embed(public_path('/assets/images/logo.png')) }}" ></div>
</body>
</html>
//==============================================
**I want:**
<html>
<body>
<div><img src="embed swiftmailfile~~~~~~" ></div>
</body>
</html>
So, how can I return the view using HTML
so that it can be passed to the variable?
You can try this:
Just pass src to view
public function build()
{
$src = $message->embed(public_path('/assets/images/logo.png'));
return $this->subject( $this->subject)->view('emails.EmailTemplate', ['src' => $src]);
}
And then , render to view
<html>
<body>
<div><img src="{{ $src }}" ></div>
</body>
</html>
You are trying to render blade inside the mailable.
Instead, create the string using concatenation
$this->template = '<div><img src="' . $message->embed(public_path('/assets/images/logo.png')) . '" ></div>';
I'm trying to follow this tutorial https://laravelcode.com/post/laravel-full-calendar-tutorial-example-using-maddhatter-laravel-fullcalendar. I completed every steps but the calendar still does not appear, only the Laravel header and the "Full Calendar Example" writing but not the calendar itself or if I remove "extends('layout.php')" nothing appears. :( What could be the problem? I hope someone can give a quick answer. Sorry if it's a bad question here.
My code:
config/app.php
'providers' => [
.....
.....
MaddHatter\LaravelFullcalendar\ServiceProvider::class,
],
'aliases' => [
.....
.....
'Calendar' => MaddHatter\LaravelFullcalendar\Facades\Calendar::class,
]
database/migrations/CreateEventsTable
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEventsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->date('start_date');
$table->date('end_date');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop("events");
}
}
app/Event.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
protected $fillable = ['title','start_date','end_date'];
}
database/seeds/AddDummyEvents.php
use Illuminate\Database\Seeder;
use App\Event;
class AddDummyEvent extends Seeder
{
public function run()
{
$data = [
['title'=>'Demo Event-1', 'start_date'=>'2017-09-11', 'end_date'=>'2017-09-12'],
['title'=>'Demo Event-2', 'start_date'=>'2017-09-11', 'end_date'=>'2017-09-13'],
['title'=>'Demo Event-3', 'start_date'=>'2017-09-14', 'end_date'=>'2017-09-14'],
['title'=>'Demo Event-3', 'start_date'=>'2017-09-17', 'end_date'=>'2017-09-17'],
];
foreach ($data as $key => $value) {
Event::create($value);
}
}
}
routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('events', 'EventController#index');
app/Http/Controllers/EventController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Calendar;
use App\Event;
class EventController extends Controller
{
public function index()
{
$events = [];
$data = Event::all();
if($data->count()) {
foreach ($data as $key => $value) {
$events[] = Calendar::event(
$value->title,
true,
new \DateTime($value->start_date),
new \DateTime($value->end_date.' +1 day'),
null,
// Add color and link on event
[
'color' => '#f05050',
'url' => 'pass here url and any route',
]
);
}
}
$calendar = Calendar::addEvents($events);
return view('fullcalendar', compact('calendar'));
}
}
resources/views/fullcalendar.blade.php
#extends('layouts.app')
#section('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>
#endsection
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Full Calendar Example</div>
<div class="panel-body">
{!! $calendar->calendar() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
#section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>
{!! $calendar->script() !!}
#endsection
Unsure why it was left out of the tutorial, but they didn't have you set up a layout blade file. They also forgot to include jquery. If you change fullcalendar.blade.php to the following code it works.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
ref="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css"/>
<body>
<div class="container" style="margin-top: 100px">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Full Calendar Example</div>
<div class="panel-body">
{!! $calendar->calendar() !!}
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js"></script>
{!! $calendar->script() !!}
</html>
Look in the EventController in the calender() function
The return view() is trying to return "calender", change it to calendar to match the view name you created in views.
First i created the Admin model in which i implemented it using Authenticable Admin.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
class Admin extends Model implements \Illuminate\Contracts\Auth\Authenticatable
{
//
use Authenticatable;
}
then i created the migration :
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->rememberToken();
$table->string('email');
$table->string('password');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('admins');
}
}
Replaced the Users model in config/auth.php with Admin Model :
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
AdminController.php
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Auth;
class AdminController extends Controller{
public function getIndex()
{
$posts= Post::orderBy('created_at','desc')->take(3)->get();
return view('backend.index')->with(['posts'=>$posts]);
}
public function getLogin(){
return view('backend.login');
}
public function postLogin(Request $request){
$this->validate($request,[
'email'=>'required|email',
'password'=>'required'
]);
dd(Auth::attempt(['email'=>$request['email'],'password'=>$request['password']]));
if(!Auth::attempt(['email'=>$request['email'],'password'=>$request['password']])){
return redirect()->back()->with(['fail'=>'Could Not Log You In']);
}
return redirect()->route('admin.index');
}
public function getLogout(){
Auth::logout();
return redirect()->route('blog.index');
}
}
web.php
Route::get('/admin/login',[
'uses'=>'AdminController#getLogin',
'as'=>'admin.login'
]);
Route::post('/admin/login',[
'uses'=>'AdminController#postLogin',
'as'=>'admin.login'
]);
login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Admin Area</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{URL::to('css/bootstrap.min.css')}}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="{{URL::to('js/bootstrap.min.js')}}"></script>
#yield('styles')
</head>
<body>
<div class="container">
<div class="container-fluid">
#include('includes.info-box')
<form method="post" action="{{route('admin.login')}}">
<div class="form-group">
<label for="email">Email: </label>
<input type="email" class="form-control" id="email" name="email"
{{$errors->has('email')?'class=alert alert-danger':'' }}
value="{{Request::old('email')}}">
</div>
<div class="form-group">
<label for="password">Password: </label>
<input type="password" class="form-control" id="password" name="password"
{{$errors->has('password')?'class=alert alert-danger':'' }}
>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Login</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</div>
</form>
</div>
</div>
</body>
</html>
so when i tried to login and dd the Auth Attempt it is returning false i have a user with email test#123.com and password test :
created the user using seeder :
<?php
use Illuminate\Database\Seeder;
class AdminTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
$admin = new \App\Admin;
$admin->email='test#123.com';
$admin->password='test#123.com';
$admin->save();
}
}
So for your seeder.
$admin = new \App\Admin;
$admin->email='test#123.com';
$admin->password='test#123.com';
$admin->save();
the password should be hashed using bcrypt.
$admin->password = bcrypt('test#123.com');
but as you've said, you're trying 'test' as the password, so it should be:
$admin->password = bcrypt('test');
that should work.
the reason is, Auth::attempt hashes the entered password using bcrypt.
So if the stored password in your database is not bcrypt-ed, Auth::attempt
will fail to match the two passwords.
For example you put test as the password, plain text, if you try to login to laravel using Auth::attempt using password = 'test', string 'test' will be compared against the bcrpyt version of 'test'.
I try to made a crud but I found this error :
Undefined variable: playlists (View: C:\xampp\htdocs\laravel53\resources\views\pages\playlist\index.blade.php)
create is working... but index no...
I am using laravel 5.4
and this is my controller :
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth,
Response,
Storage,
Session,
Redirect,
Validator,
Image,
Input;
use App\Playlist;
class PlaylistsController extends Controller {
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index')->withPlaylists($playlists);
}
public function create() {
return view('pages.playlist.create');
}
public function store(\Illuminate\Http\Request $request) {
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'authors' => 'required',
'date' => 'required',
'url' => 'required',
'menssage' => 'required',
]);
$input = $request->all();
Playlist::create($input);
Session::flash('flash_message', 'Video/img successfully added!');
return view('admin');
}
public function show($id) {
$playlists = Playlist::findOrFail($id);
return view('pages.playlist.show')->withPlaylits($playlists);
}
public function edit($id) {
$playlists = Playlist::findOrFail($id);
return view('pages.playlist.edit')->withPlaylits($playlists);
}
public function update(Request $request, $id) {
$playlists = Playlist::findOrFail($id);
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'authors' => 'required',
'date' => 'required',
'url' => 'required',
'menssage' => 'required',
]);
$input = $request->all();
$playlists ->fill($input)->save();
Session::flash('flash_message', 'Task successfully added!');
return redirect()->back();
}
public function destroy($id) {
$playlists = Playlist::findOrFail($id);
$playlists ->delete();
Session::flash('flash_message', 'Task successfully deleted!');
return redirect()->route('playlist.index');
}
}
My index :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
#section('content')
<h1>Task List</h1>
<p class="lead">Here's a list of all your tasks. Add a new one?</p>
<hr>
#foreach($playlists as $playlist)
<h3>{{ $playlist->title }}</h3>
<p>{{ $playlist->description}}</p>
<p>{{ $playlist->authors}}</p>
<p>{{ $playlist->date}}</p>
<p>{{ $playlist->url}}</p>
<p>{{ $playlist->menssage}}</p>
#endforeach
<p>
View Task
Edit Task
</p>
<hr>
#stop
#extends('layouts.master')
#section('content')
</body>
</html>
Controller
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index')->with(['data', $playlists]);
}
In your index blade, just do to understand, remove blade related codes.
<?php
print_r($data);
?>
OR
You can simply do
public function index() {
$playlists = Playlist::all();
return view('pages.playlist.index',['data'=>$playlists]);
}
and in your index blade just do print_r($data) and see the result and then loop through it accordingly. Remove everything from index blade because you are extending master blade there. So remove everything (HTMLs) and just write a line of code in index blade i.e. print_r($data).
You should write this in your view
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
#section('content')
<h1>Task List</h1>
<p class="lead">Here's a list of all your tasks. Add a new one?</p>
<hr>
#foreach($playlists as $playlist)
<h3>{{ $playlist->title }}</h3>
<p>{{ $playlist->description}}</p>
<p>{{ $playlist->authors}}</p>
<p>{{ $playlist->date}}</p>
<p>{{ $playlist->url}}</p>
<p>{{ $playlist->menssage}}</p>
<p>
View Task
Edit Task
</p>
#endforeach
<hr>
#stop
#extends('layouts.master')
#section('content')
</body>
</html>
And In your controller method you write this
public function index() {
$playlists = Playlist::all();
return View('pages.playlist.index', comapct('playlists'));
}
THIS WILL SOLVE YOUR PROBLEM
I'm trying to display flash data but it's not showing properly. It's showing:
{{ Session::get('flash_message') }}
but it should be the message
"Your article has been created"
What's wrong with my code? Thanks!
In my controller I have:
public function store(ArticleRequest $request)
{
Auth::user()->articles()->create($request->all());
\Session::flash('flash_message', 'Your article has been created');
return redirect('articles');
}
My app.blade.php is:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>App Name - #yield('title')</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ elixir('css/all.css') }}">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div class="container">
#if(Session::has('flash_message'))
<div class="alert alert-success">{{ Session::get('flash_message') }}</div>
#endif
#yield('content')
</div>
#yield('footer')
</body>
</html>
In my route.php I have the following: Curly braces display content as string not variables.
<?php
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
Route::get('/', function() {
return 'Home Page';
});
Route::get('blade', function () {
return view('about');
});
Route::get('about', 'HelloWorld#about');
Route::get('foo', ['middleware' => 'manager', function() {
return 'this page may only be viewed by managers';
}]);
Route:resource('articles', 'ArticlesController');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
If you have this in your route.php:
Blade::setContentTags('<%', '%>');
then that means you cannot use curly brackets for blade content. Try this instead:
#if(Session::has('flash_message'))
<div class="alert alert-success">
<% Session::get('flash_message') %>
</div>
#endif
or simply remove the setContentTags() call from your route.php.
You can make a multiple messages and with different types.
Follow these steps below:
Create a file: "app/Components/FlashMessages.php"
namespace App\Components;
trait FlashMessages
{
protected static function message($level = 'info', $message = null)
{
if (session()->has('messages')) {
$messages = session()->pull('messages');
}
$messages[] = $message = ['level' => $level, 'message' => $message];
session()->flash('messages', $messages);
return $message;
}
protected static function messages()
{
return self::hasMessages() ? session()->pull('messages') : [];
}
protected static function hasMessages()
{
return session()->has('messages');
}
protected static function success($message)
{
return self::message('success', $message);
}
protected static function info($message)
{
return self::message('info', $message);
}
protected static function warning($message)
{
return self::message('warning', $message);
}
protected static function danger($message)
{
return self::message('danger', $message);
}
}
On your base controller "app/Http/Controllers/Controller.php".
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use App\Components\FlashMessages;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
use FlashMessages;
}
This will make the FlashMessages trait available to all controllers that extending this class.
Create a blade template for our messages: "views/partials/messages.blade.php"
#if (count($messages))
<div class="row">
<div class="col-md-12">
#foreach ($messages as $message)
<div class="alert alert-{{ $message['level'] }}">{!! $message['message'] !!}</div>
#endforeach
</div>
</div>
#endif
On "boot()" method of "app/Providers/AppServiceProvider.php":
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Components\FlashMessages;
class AppServiceProvider extends ServiceProvider
{
use FlashMessages;
public function boot()
{
view()->composer('partials.messages', function ($view) {
$messages = self::messages();
return $view->with('messages', $messages);
});
}
...
}
This will make the $messages variable available to "views/partials/message.blade.php" template whenever it is called.
On your template, include our messages template - "views/partials/messages.blade.php"
<div class="row">
<p>Page title goes here</p>
</div>
#include ('partials.messages')
<div class="row">
<div class="col-md-12">
Page content goes here
</div>
</div>
You only need to include the messages template wherever you want to display the messages on your page.
On your controller, you can simply do this to push flash messages:
use App\Components\FlashMessages;
class ProductsController {
use FlashMessages;
public function store(Request $request)
{
self::message('info', 'Just a plain message.');
self::message('success', 'Item has been added.');
self::message('warning', 'Service is currently under maintenance.');
self::message('danger', 'An unknown error occured.');
//or
self::info('Just a plain message.');
self::success('Item has been added.');
self::warning('Service is currently under maintenance.');
self::danger('An unknown error occured.');
}
...
Hope it'l help you.