Laravel: Errors/Messages not being fetched in view - laravel-blade

I'm doing the following:
if(Request::get('file') == 'yes' && Request::file('file_name') == null){
return Redirect::back()
->withInput()
->withErrors("You did not select file")
->with('message', 'There were validation errors.');
return false;
}
But it is not fetching back to view no matter what. I tried to use errors and $message. Nothing worked. Debugger shows that message are being stored in the session.
In view I did the following:
<div style="margin-top: 10%;" class="alert alert-danger">
<? print_r($message); ?>
show here
</div>

Because you are redirecting back, you have to access your variable with the session() helper or the Session::get() facade.
You should then do something like
{{ session('message') }}
In your case, session('message') is not an array so no need to use print_r().

Related

Missing required parameters for [Route: {$route->getName()}] [URI: {$route->uri()}]."

in new to laravel and Im trying to set up an edit blade using resource controller . ( using laravel 5.7) but it is throwing an error like this
Missing required parameters for [Route: home.hotels.update] [URI: home/hotels/{hotel}]. (View: C:\xamp\....\.....\edit.blade.php)
Please note:
when i hover over edit button it is correctly pointing to the id's and
when i tries to echo a fieldname inside my "edit function"in controller it returns the correct page but "blank" . can some one tell me wher this error comming from and if possible how to fix this
code in my index blade ( part relating to the edit)
#foreach($hotels as $c)
<tr>
<td>{{$c->hotelid}}</td>
<td>{{$c->hotelname}}</td>
<td>{{$c->city}}</td>
<td>{{$c->location}}</td>
<td>{{$c->singleroom}}</td>
<td>{{$c->doubleroom}}</td>
<td>{{$c->deluxroom}}</td>
<td>{{$c->deluxdouble}}</td>
<td>{{$c->superiorsuit}}</td>
<td><a href="{{route('home.hotels.edit',$c->id)}}"class="btn btn-info" >Update </a>
my edit blade
im passing the entries like this
<form method="post" action="{{route('home.hotels.update',$hotels->id)}}">
#csrf
{{ method_field('PUT') }}
<div class="form-group">
<div class="row">
<label class="col-md-6">Hotel ID</label>
<div class="col-md-6"><input type="text" name="hotelid" class="form-control" value="{{$hotels->hotelid}}"> </div>
</div>
......... rest of the input fields follows........
controller functions
public function index()
{
$arr['hotels']=hotels::all();
return view('admin.hotels.index')->with($arr);
}
my update function also has the same code as store ------
public function store(Request $request, hotels $hotels)
{
$hotels->hotelid=$request->hotelid;
$hotels->hotelname=$request->hotelname;
...........other fields..................
$hotels->save();
return redirect('home/hotels');
}
public function edit(hotels $hotels )
{
$arr['hotels'] = $hotels;
return view('admin.hotels.edit')->with($arr);
}
and my routes
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('home/users', 'Admin\UsersController',['as'=>'home']);
Route::resource('home/hotels', 'Admin\HotelsController',['as'=>'home']);

Twig: Render view with different parameters based on one Controller action

this might be a stupid question but maybe you can still help me out here.
What I want: I have a Twig template, that has tabs in it (using Bootstrap tab panels) and now I want to render the tab contents using one Action from one Controller but with different parameters.
So basically, this controller action should take some param "type" and then return different results based on this type. The goal is to not have 2 Controllers to render the twig view that do almost the same except extracting different information based on the param "type.
However, I cannot get it to work. It's either that both tabs render the same results since apparently the view is only rendered once OR that I get exceptions in the twig template at time of rendering.
What would be the right way to approach this problem?
Many thanks.
There are multiple ways to achieve this. You can use if/else statements in your Twig template, but you can also set the template in you controller. It's up to you what suits best.
Method 1: custom template
By default, Symfony uses 'foobar.html.twig' on your foobarAction() method, but you can override this in your method:
public function recentArticlesAction($max = 3)
{
// make a database call or other logic
// to get the "$max" most recent articles
$articles = ...;
return $this->render(
'article/recent_list.html.twig',
array('articles' => $articles)
);
}
(warning: example from How to Embed Controllers in a Template, but the article itself has nothing to do with your question)
You can set a variable (for example $templateName) and change it:
$templateName = 'recent_list.html.twig';
if ($admin) {
$templateName = 'another_template.html.twig';
}
//or using parameters from you Request
if ($type = $request->request->get('type')) {
$templateName = $type . '.html.twig';
}
return $this->render(
$templateName,
array('articles' => $articles)
);
Method 2: using Twig
Controller:
public function foobarAction(Request $request)
{
return [
'type' => $request->request->get('type');
];
}
You Twig template:
{% if type == 'foo' %}
<h1>Foo!</h1>
<p>Hi, welcome you the foo page!</p>
{% elseif type == 'bar' %}
<h1>Bar!</h1>
<p>Hi, you've reached the Bar page.</p>
{% else %}
<h1>Error!</h1>
<p>Type not found.</p>
{% endif %}
Try render manually each view:
if ($type) {
return $this->render('home/template.html.twig', array('data' => $data));
}
return $this->render('home/another.html.twig', array('another_data' => $another_data));
Many thanks for the answers here, but they did not really helped me. Next time I try to add more code examples ;)
My goal was to render from 1 action into 1 template but with different parameters and render those different contents as partials in the parent view.
Example: Given a template called "view.html.twig" that includes 2 times the template "myPartial.html.twig", but first time with param and second time without param. Based on this param different contents should be returned.
My question was now, why apparently only the first action is rendered in Symfony as both my partial views had the same content.
So this is what I did now:
1 Controller, 2 Actions, both call a 3rd action to fetch the data and return the values to the calling action. Then both actions call the render method with the values rendered from the 3rd action.
This is what it looks now:
<div class="tab-content clearfix">
<div class="tab-pane" id="1b">
{% render controller('MyBundle:MyController:list1') %}
</div>
<div class="tab-pane" id="2b">
{% render controller('MyBundle:MyController:list2', {'type' : 1}) %}
</div>
But what I wanted to achieve was to do something like this (which did not work because then both tabs would show the same content):
<div class="tab-content clearfix">
<div class="tab-pane" id="1b">
{% render controller('MyBundle:MyController:list') %}
</div>
<div class="tab-pane" id="2b">
{% render controller('MyBundle:MyController:list', {'type' : 1}) %}
</div>
Which I find confusing since in both times "render" is called, so I would expect that the Controller is called in both times so that also the partial view in the controller is rendered both times. But apparently this was not the case :( The Controller itself looks something like this:
public function list1Action()
{
$twigVars = //do something to build the twig vars without param;
return $this->render('#MyBundle/Test/partial_list.html.twig', array(
'vars' => $twigVars,
));
}
public function list2Action($param)
{
$twigVars = //do something to build the twig vars with param;
return $this->render('#MyBundle/Test/partial_list.html.twig', array(
'vars' => $twigVars,
));
}
While what I wanted was something like this:
public function listAction($param = '')
{
if ($param) {
$twigVars = //do something to return the twig vars with param;
} else {
$twigVars = //do something else to return twig vars without param;
}
return $this->render('#MyBundle/Test/partial_list.html.twig', array(
'vars' => $twigVars,
));
}

After return redirect to a page the variable doesnot show on view page

In controller i have this code. When i want to show company variable on view it gives the error.
This is my controller.
public function login(Request $request){
$email = $request->input('email');
$password = $request->input('password');
$validation = array(
'email' =>'required',
'password' => 'required');
//dd($email);
$validator = Validator::make($request->all(), $validation);
if ($validator->fails()) {
$messages = $validator->messages();
return redirect('login_with_assismo')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$admin = DB::table('admin')
->where('email',$email)
->where('password', $password)
->where('is_admin', 1)
->first();
if (!empty($admin)) {
$company = DB::table('company_details')
->where('id', $admin->company_id)
->pluck('company_name');
if (!empty($company)) {
return redirect('company_details')->with('company', $company);
}
}
}
}
and this is my view
<input type="text" name="company_name" class="form-control" placeholder="Company name" value = "{{ company }}">
This is the error when i execute this code:
Use of undefined constant company_name - assumed 'company_name' (View: /opt/lampp/htdocs/assismo/resources/views/company_details.blade.php)
The undefined constant error means that you probably tried something like
<div><!-- or other html -->
{{ company_name}}
</div><!-- ... -->
Even though it should be
<div><!-- or other html -->
{{ $company_name}}
</div><!-- ... -->
Howveer, it does not seem you return a company name variable at all so probably it should be
<div><!-- or other html -->
{{ $company }}
</div><!-- ... -->
Additional remarks:
Your code is highly insecure. You should never ever use this in a productive enviroment. You dont crypt the password or anything. It actually seems like your passwords are stored plain.
You should also consider to write your own requests (php artisan:make request) and move validation somewhere else.
I also don't see a reason to use DB Facade here instead of the actual Object you are interested in.

Meteor: single post view, via id and flow router is not parsing any data from the collection

Im trying to open a single record from my #each loop of items into its own view by clicking a link that says 'see more', which will take me to the single article. I set up my Flow router and its working but i cannot see the data that's supposed to come in.
the template helper for the single article looks like this
Template.collectionSingle.helpers({
articles: function () {
var id = FlowRouter.getParam('_id')
return theCollection.findOne({_id: id});
}
});
}
my route looks like this
FlowRouter.route('/collection/:_id', {
name: 'collection',
action() {
BlazeLayout.render("AppLayout", {main: "collectionSingle"});
}
});
and the template "collectionSingle" looks like this
<template name="collectionSingle">
<h1>{{title}}</h1>
<h1>This is a test</h1>
<img src="{{thumbnail}}" alt="" />
</template>
when i navigate to http://localhost:3000/collection/thePublication-0
all i see is the test message 'This is a test', but i don't see the {{title}} nor the thumbnail.
furthermore, when i change:
return theCollection.findOne({_id: id});
to another one of my collections :
return OtherCollection.findOne({_id: id});
http://localhost:3000/collection/thePublication-0
remains the same.
how can i successfully have a single articles page for each of my articles and have them linked properly with flow router?
You need to actually use your template helper that is returning the data context:
<template name="collectionSingle">
<h1>{{title}}</h1>
<h1>This is a test</h1>
{{#with articles}}
<img src="{{thumbnail}}" alt="" />
{{/with}}
</template>
Since your articles helper returns a single document you use {{#with articles}}. If it returned a cursor or array you would loop over that with {{#each articles}}. The normal convention is to use the singular form for the former, the plural for the latter.

this.userId results in an undefined error

I have a postItem template which shows an edit and delete button when it is an own post for the logged in user:
<div class="page-actions">
{{#if ownPost}}
<a class="btn btn-default" href="{{pathFor 'postEdit'}}">edit</a>
<a class="btn btn-danger delete" href="#">delete</a>
{{/if}}
</div>
The ownPost helper looks like this:
Template.postItem.helpers({
ownPost: function() {
return this.userId === Meteor.userId();
}
});
But this.userId returns undefined. I guess it has something to do with the this context, but I'm not entirely sure what is going wrong here?
You'll need to console.log(this) to check its context, and following that should check that you're a) publishing the data that you want (are you using pub/sub with specified fields or still prototyping with autopublish/insecure etc?).
Lastly I'd check whether you're saving the data correctly to the document in your collection, but obviously only the user collection inherently possesses a userid.
Inside of template helpers like this, the this keyword will refer to object that is populating the template.

Resources