Flash data in Laravel 5 - laravel

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.

Related

How to render a mail with HTML variable?

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>';

Two types of likes with Cookie

I need any user to be able to like it every 24 hours
I wrote a function for this
const LIKE_HEART = 'like_heart';
const LIKE_FINGER = 'like_finger';
public static $types = [self::LIKE_HEART, self::LIKE_FINGER];
public function setLikes() {
$likes = Cookie::get($types);
$hours = 24;
if ($likes) {
self::where('id', $article->id)
->where('updated_at', '<', Carbon::now()->subHours($hours))
->increment($types);
}
}
But I have two fields in my database, like_heart and like_finger, these should be two types of likes. How can I rewrite my function into a method so that I can only choose one type of like out of two?
An array of the following type must be serialized in cookies:
$r = [
'1' => [
'like_heart' => '2021-09-28 22:02:01',
'like_finger' => '2021-11-28 11:12:34',
],
'2' => [
'like_finger' => '2021-11-28 11:12:34',
],
];
where 1, 2 is the article ID. Date - the date the like was added by current users
The current date is compared with the date in this cookie for a specific article, and if it is less than 24 hours old or missing, add +1 to the corresponding like in the article and add / change information in the like.
article.blade
<div class="blog-wrapper">
<div class="container">
<div class="article">
<p><b>{!! $article->title !!}</b></p>
<p><b>{!! $article->subtitle !!}</b></p>
<picture>
<source srcset="{{ $article->image_list_mobile }}" media="(max-width: 576px)" alt="{{ $article->image_mobile_alt }}" title="{{ $article->image_mobile_title }}">
<source srcset="{{ $article->image_list }}" alt="{{ $article->image_alt }}" title="{{ $article->image_title }}">
<img srcset="{{ $article->image_list }}" alt="{{ $article->image_alt }}" title="{{ $article->image_title }}">
</picture>
<p><b>{{ date('d F Y', strtotime($article->published_at)) }}</b></p>
<p><b>{{ $article->getTotalViews() }} Views</b></p>
<p><b>{{ $allArticleCommentsCount }} Comments</b></p>
</div>
Like Heart
Like Finger
<div class="comments">
<div class="recommend-title"><p><b>Comments ({{ $allArticleCommentsCount }})</b></p></div>
#foreach($article_comments as $article_comment)
<p><b>{!! $article_comment->name !!}</b></p>
<p><b>{!! $article_comment->text !!}</b></p>
<p><b>{{ date('d F Y', strtotime($article_comment->date)) }}</b></p>
#endforeach
</div>
</div>
</div>
controller
public function index(Request $request, $slug)
{
$article = Article::where('slug', $slug)->first();
if(!$article){
return abort(404);
}
$viewed = Session::get('viewed_article', []);
if (!in_array($article->id, $viewed)) {
$article->increment('views');
Session::push('viewed_article', $article->id);
}
$allArticleCommentsCount = ArticleComment::where('article_id', $article->id)->count();
$article_comments = ArticleComment::where('article_id', $article->id)->get();
return view('article', compact('article', 'article_comments', 'allArticleCommentsCount'));
}
public function postLike() {
if ($like = request('like')) {
$articleId = request('article_id');
if (User::hasLikedToday($articleId, $like)) {
return response()
->json([
'message' => 'You have already liked the Article #'.$articleId.' with '.$like.'.',
]);
}
$cookie = User::setLikeCookie($articleId, $like);
return response()
->json([
'message' => 'Liked the Article #'.$articleId.' with '.$like.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
}
Article model
class User extends Authenticatable
{
// ...
public static function hasLikedToday($articleId, string $type)
{
$articleLikesJson = \Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
// Check if there are any likes for this article
if (! array_key_exists($articleId, $articleLikes)) {
return false;
}
// Check if there are any likes with the given type
if (! array_key_exists($type, $articleLikes[$articleId])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$articleId][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public static function setLikeCookie($articleId, string $type)
{
// Initialize the cookie default
$articleLikesJson = \Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
// Update the selected articles type
$articleLikes[$articleId][$type] = today()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
}
route
Route::get('/article', function () {
$articleLikesJson = \Cookie::get('article_likes', '{}');
return view('article')->with([
'articleLikesJson' => $articleLikesJson,
]);
});
Route::get('article/{id}/like', 'App\Http\Controllers\ArticleController#postLike');
First of all, you should never store any logic in the client side. A great alternative for this kind of feature would be using the Laravel Aquantances package.
https://laravel-news.com/manage-friendships-likes-and-more-with-the-acquaintances-laravel-package
Anyway, since you want to do it with cookies;
We can actually do this a lot easier than thought.
Articles.php
class User extends Authenticatable
{
// ...
public static function hasLikedToday($articleId, string $type)
{
$articleLikesJson = \Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
// Check if there are any likes for this article
if (! array_key_exists($articleId, $articleLikes)) {
return false;
}
// Check if there are any likes with the given type
if (! array_key_exists($type, $articleLikes[$articleId])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$articleId][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public static function setLikeCookie($articleId, string $type)
{
// Initialize the cookie default
$articleLikesJson = \Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
// Update the selected articles type
$articleLikes[$articleId][$type] = today()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
}
The code above will allow us to is a user has liked an article and generate the cookie we want to set.
There are a couple important things you need to care about.
Not forgetting to send the cookie with the response.
Redirecting back to a page so that the cookies take effect.
I've made a very small example:
routes/web.php
Route::get('/test', function () {
$articleLikesJson = \Cookie::get('article_likes', '{}');
if ($like = request('like')) {
$articleId = request('article_id');
if (User::hasLikedToday($articleId, $like)) {
return redirect()->back()
->with([
'success' => 'You have already liked the Article #'.$articleId.' with '.$like.'.',
]);
}
$cookie = User::setLikeCookie($articleId, $like);
return redirect()->back()
->withCookie($cookie)
->with([
'success' => 'Liked the Article #'.$articleId.' with '.$like.'.',
]);
}
return view('test')->with([
'articleLikesJson' => $articleLikesJson,
]);
});
resources/views/test.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
</head>
<body>
<div class="container">
#if (session('success'))
<div class="alert alert-success" role="alert">
{{ session('success') }}
</div>
#endif
<pre>{{ $articleLikesJson }}</pre>
<div class="row">
#foreach (range(1, 4) as $i)
<div class="col-3">
<div class="card">
<div class="card-header">
Article #{{ $i }}
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
<a href="/test?like=heart&article_id={{ $i }}" class="btn btn-primary">
Like Heart
</a>
<a href="/test?like=finger&article_id={{ $i }}" class="btn btn-primary">
Like Finger
</a>
</div>
<div class="card-footer text-muted">
2 days ago
</div>
</div>
</div>
#endforeach
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>
</body>
</html>
Post Update:
1- Remove the range()
2- Update the route of these links (to where you put the logic for liking)
3- Below I've added an example for route Route::post('article/{id}/like', [SomeController::class, 'postLike'])
Like Heart
Like Finger

Laravel Full Calendar

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.

Laravel 5.2.45 - empty $errors variable in views

Problem:
The $errors variable is empty in the views. There's talk that this has been fixed in 5.2 so hopefully the problem is on my end.
Environment:
Mac OS X
Laravel 5.2.45
The Codez:
Routes.php
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
AlleleController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Allele;
class AlleleController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
// All methods require authentication except index.
$this->middleware('auth', ['except' => ['index']]);
}
/**
* Root page.
*
* #return Response
*/
public function index() {
return view('welcome');
}
/**
* Create a new allele.
*
* #param Request $request
* #return Response
*/
public function store(Request $request) {
$allele = new Allele();
// Get all input as an array.
$input = $request->all();
// Validate input.
if ($allele->validate($input)) {
// Valid input. Write to database.
// The inserted model instance is returned.
$result = $allele::create($input);
if ($result) {
// Insert successful.
$message = array('message' => 'Data added!');
return view('home', $message);
} else {
// Insert failed. Send errors to view.
$errors = array('errors' => 'Error saving data.');
return view('home', $errors);
}
} else {
// Invalid input. Get errors.
$errors = $allele->errors();
// Send errors to view.
return view('home', $errors);
}
}
}
?>
HomeController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index() {
return view('home');
}
}
Model: Allele.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Allele extends Validation {
/**
* The attributes that are mass assignable.
*/
protected $fillable = ['allele'];
/**
* Validation rules.
*/
protected $rules = array (
'allele' => 'required|max:20',
);
}
Model: Validation.php
<?php
namespace App;
use Validator;
use Illuminate\Database\Eloquent\Model;
class Validation extends Model {
protected $rules = array();
protected $errors;
public function validate($input) {
// Make a new validator object.
$v = Validator::make($input, $this->rules);
// Check for failure.
if ($v->fails()) {
// Set errors and return false.
$this->errors = $v->errors();
return false;
}
// Validation passed.
return true;
}
// Retrieves the errors object.
public function errors() {
return $this->errors;
}
}
View: views/common/errors.blade.php
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
View: views/home.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dashboard</div>
<div class="panel-body">
You are logged in!
</div>
</div>
</div>
</div>
</div>
<!-- Create New Allele -->
<div class="panel-body">
<!-- Display Validation Errors -->
#include('common.errors')
<!-- New Allele Form -->
<form action="{{ url('allele') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Allele Name -->
<div class="form-group">
<label for="allele-name" class="col-sm-3 control-label">Allele</label>
<div class="col-sm-6">
<input type="text" name="allele" id="allele-name" class="form-control">
</div>
</div>
<!-- Add Allele Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Allele
</button>
</div>
</div>
</form>
</div>
#endsection
All validation methods should be placed inside web middleware . I do not see any other error. Replace your route.php like this.
Route::group(['middleware' => ['web']], function ()
{
Route::get('/', 'AlleleController#index');
Route::get('/register', function () {
return view('auth.register');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::get('/alleles', 'AlleleController#index');
Route::post('/allele', 'AlleleController#store');
Route::delete('/allele/{allele}', 'AlleleController#destroy');
});

Individual profile pages and searches Laravel 5.2

Having a real confusing time with this project, my issue is I'm trying to get my search working but for some reason its not pulling results from my query when there is that information in the database, also when I click on the username in the top corner of my page, it should redirect to the user page but instead I get this error "NotFoundHttpException in Application.php line 879:" with the URl looking like this "http://localhost/WorldLink/users/firstName%20=%3E%20Auth::user%28%29-%3EfirstName" and I have exhausted all other means of trying to fix it so I'm back for some help! my code is below Im using laravel 5.2:
Users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
protected $table = 'users';
protected $fillable = [
'id', 'firstName', 'lastName', 'bio', 'homeLocation', 'currentLocation', 'email', 'password',
];
public function getName()
{
if ($this->firstName && $this->lastName) {
return "{$this->firstName} {$this->lastName}";
}
if ($this->firstName) {
return $this->firstName;
}
return null;
}
public function getNameOrLocation()
{
return $this->getName() ?: $this->currentLocation;
}
public function getFirstNameOrLocation()
{
return $this->firstName ?: $this->currentLocation;
}
public function getAllAvatarsUrl()
{
return "https://www.gravatar.com/avatar/{{ md5($this->email) }}?d=mm&s=40";
}
}
SearchController.php:
<?php
namespace App\Http\Controllers;
use DB;
use App\Users;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class SearchController extends BaseController
{
public function getResults(Request $request)
{
$query = $request->input('query');
if (!$query) {
return back();
}
$users = Users::where(DB::raw("CONCAT(firstName, ' ', lastName)"), '
LIKE', "%{$query}%")
->orWhere('currentLocation', 'LIKE', "%{$query}%")
->get();
return view('search/results')->with('users', $users);
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class ProfileController extends BaseController
{
public function getProfile($firstName)
{
$users = User::where('firstName', $firstName)->first();
if (!$users) {
abort(404);
}
return view('profile.index')
->with('users', $users);
}
}
userblock.blade.php
<div class="media">
<a class="pull-left" href="{{ route('profile/index', ['firstName' => $users->firstName]) }}">
<img class="media-object" alt="{{ $users-getNameOrLocation() }}" src="{{ $users->getAllAvatarsUrl() }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ $users->getNameOrLocation() }}</h4>
</div>
#if ($users->currentLocation)
<p>{{ $users->currentLocation }}</p>
#endif
results.blade.php
#extends('layouts.app')
#section('content')
<h3>Search Results for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No Results Found</p>
#else
<div class="row">
<div class="col-lg-12">
#foreach ($users as $user)
#include('users/partials/userblock')
#endforeach
</div>
</div>
#endif
#endsection
And finally my two routes, the problem is connected in here somewhere I just cant find where its going wrong.
Route::get('/search', [
'uses' => '\App\Http\Controllers\SearchController#getResults',
'as' => 'search/results',
]);
Route::get('/users/{firstName}', [
'uses' => '\App\Http\Controllers\ProfileController#getProfile',
'as' => 'profile/index',
]);
The Link:
#if (Auth::guest())
<li>Login</li>
<li>Register</li>
#else
<ul class="nav navbar-nav">
<form class="navbar-form navbar-left" role="search" action="{{ route('search/results') }}">
<input type="text" class="form-control" placeholder="Search" name="query">
</form>
<li>{{ Auth::user()->firstName }}</li>
<li>Timeline</li>
<li>Link</li>
<li>Journeys <span class="journey-num">{{ Auth::user()->journeys }}</span></li>
<li>Forum</li>
</ul>
Defo quoting incorrectly
....
<li>{{ Auth::user()->firstName }}</li>
....
Note closing ' moved to after firstName array key.
That should at least fix the link

Resources