I created a variable in my controller so I can inject a Page Title to my pages. I have other variables setup exactly the same way and they work, but for some reason I am getting an Undefined variable: pageTitle on the new variable.
ShowUsers.php
public function render()
{
...
return view('livewire.show-users', [
'users' => $query->with('documents')->paginate($this->perPage),
'currentUser' => auth()->user(),
'pageTitle' => 'Users',
]);
}
page-header.blade.php
...
<h1 class="ml-3 text-2xl font-bold leading-7 text-gray-900 sm:leading-9 sm:truncate">
{{ $pageTitle }}
</h1>
...
You are not binding variable pageTitle into the page-header blade file. You can bind variables using Laravel Blade.
liveware/show-users.blade.php
#extends('page-header', ['pageTitle' => 'Users'])
Related
I am trying to code the edit route for laravel and for some reason keep getting the error "Trying to get property of non-object laravel". The Create controller works fine, however when I use the controller#update route I keep getting this error
My Controller for adding an event: (update)
public function update(Request $request, $id)
{
//create event
$my_user = my::find($id);
$my_user->programme = $request->input('programme');
$my_user->goal1 = $request->input('goal1');
$my_user->goal2 = $request->input('goal2');
$my_user->goal3 = $request->input('goal3');
$my_user->goal4 = $request->input('goal4');
$my_user->goal5 = $request->input('goal5');
$my_user->user_id = auth()->user()->id;
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
edit page
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Post</h1>
{!! Form::open(['action' => ['myUserController#update', $my_user], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Event Name')}}
{{Form::text('goal1', $my_user->goal1, ['class' => 'form-control', 'placeholder' => 'Goal One'])}}
</div>
{{Form::hidden('_method','PUT')}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Given that you are using a Route::resource you can type-hint your parameters by writing something like
public function update(Request $request, MyUser $myuser){
// The $myuser parameter comes from the Route::resource and can be verified using php artisan route:list in your terminal
// edit $my_user
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
Update after reviewing LaravelCollective documentation for Form
Thank you Sohel0415 for mentioning that you do not need to call $my_user->id for providing the route parameter with the Form facade.
You can use this method on your code:
{{ Form::open(array('url'=>'admin/users/store' , 'method' =>'POST')) }}
and your route define by this method in web.php file:
Route::post('users/store', 'admin\UserController#store');
I'm trying to output my posts and for that in a specific page I call a function with foreach to load all the posts, and the function in my controller is something like:
public function getDashboard()
{
$posts = Post::all();
return view('dashboard', ['posts' => $posts]);
}
and my route is something like this:
Route::get('/dashboard',[
'uses' => 'PostController#getDashboard',
'as' => 'dashboard'
]);
but get an error when I try to load the page when i'm not logged in
the error is something like:
Undefined variable: posts (View: C:\wamp64\www\projectname\resources\views\dashboard.blade.php)
Anything you say is highly appreciated.
(I use Laravel 5.3.26 )
Here you go this is my blade, but I don't think this is where the problem is:
#extends('layouts.master')
#section('content')
#foreach($posts as $post)
<article class="post">
<div class="media w3-border-left w3-border-blue">
<div class="media-left media-top">
</div>
<div class="media-body">
<header><h4 class="media-heading">{{ $post->title }}</h4></header>
<p>{{ $post->body }}</p>
<div class="info">
Posted by {{ $post->user->name }} on {{ $post->created_at }}
</div>
<div class="interaction">
Like |
Dislike |
Edit |
Delete
</div>
</div>
</div>
<br>
</article>
#endforeach
#endsection
Try:
public function getDashboard()
{
$posts = Post::all();
return view('dashboard', compact('posts'));
}
I'm thinking it's your authentication redirecting to a different controller method (which is not injecting the Posts).
Try a composer in your routes\web.php
View::composer( ['dashboard.blade'] , function($view) {
$action = app('request')->route()->getAction();
dump($action);
return $view->with(
[
'posts' => Post::all(), // you may need the fully qualified namespace here
]
);
});
This is a bit dirty and you won't want to keep this but it should give you some further info to go off - if you can post the output of the dump and check that posts are still injected when logged out;
Using this method the output of my dump was
array:7 [▼
"middleware" => array:2 [▼
0 => "web"
1 => "auth"
]
"uses" => "App\Http\Controllers\Admin\TestController#home"
"controller" => "App\Http\Controllers\Admin\TestController#home"
"namespace" => "App\Http\Controllers\Admin"
"prefix" => "/admin"
"where" => []
"as" => "admin.test"
]
My routes.php excerpt:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
});
My PostsController.php excerpt:
/**
* DELETE /admin/posts/{id}
*/
public function destroy($id)
{
// code
}
/**
* DELETE /admin/posts/trash
*/
public function emptyTrash()
{
// code
}
The problem is that Laravel confuses the 'trash' string in a DELETE /admin/posts/trash request as an {id} parameter. As a consequence, the destroy() method is called instead of emptyTrash(). Why and What can I do for this?
Firstly, order matters. Laravel will search the routes for a match in the order you register them. As you figured out, Laravel will take trash as an id and therefore the URI matches the resource route. Since that route is registered before your additional one, it will use the resource route.
The simplest fix is to just change that order:
Route::delete('posts/trash', [
'as' => 'posts.trash.empty',
'uses' => 'PostsController#emptyTrash'
]);
Route::resource('posts', 'PostsController', [
'except' => ['show']
]);
If you don't like that you can try to limit the parameter for your resource route to numbers only. Unfortunately you can't just add a ->where() to the resource route like you could with others.
Instead you have to define a global pattern for the route parameter. The route parameter Route::resource chooses is the resource name (in snake_case).
So this should work for you:
Route::pattern('posts', '[0-9]+');
Somewhere in your view, you should have a button or a link for actually deleting the post. The view should look something like this:
#section('content')
<div class="panel panel-default">
<div class="panel-heading clearfix">
<b>{{ $post->post_name . ' (id:' . $post->post_id . ')' }}</b><br />
<b> {{ link_to_route('overview', 'Go Back To Post List') }} </b>
<div class="pull-right">
// FORM FOR DELETING POST
{{ Form::open(array('route' => array('delete_post', $post->post_id))) }}
{{ link_to_route('edit_post', 'Edit Post', array('id' => $post->post_id), array('class' => 'post_img_button_edit')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete Post', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
<div class="pull-right">
// FORM FOR EMPTYING TRASH
{{ Form::open(array('route' => 'empty_trash')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Empty Trash', array('class' => 'post_img_button_delete')) }}
{{ Form::close() }}
</div>
</div>
/* Additional HTML code within view */
Your controller should be similar to this:
public function destroy($id)
{
$this->post->delete($id);
return \Redirect::route('overview');
}
public function emptyTrash()
{
// code for collecting and emptying Trash
}
And your routes should look similar to this:
Route::delete('admin_posts/admin_posts/{id}/destroy', array('as'=>'delete_post', 'uses'=>'PostsController#destroy'));
Route::delete('posts/trash', array('as'=>'empty_trash', 'uses'=>'PostsController#emptyTrash'));
The name of your route for actually deleting posts be 'delete_post'.
The name of your route for emptying your trash will be empty_trash
Basically you're explicitly defining your routes so that you'll avoid less ambiguity and Laravel will know which routes to take. Hopefully this information will help!
Im having a little problem that i dont understand..
My Controller:
<?php
class SearchController extends BaseController{
public function postSearch(){
$course = Input::get('course_category');
if(empty($course)){
return Redirect::route('search')
->with('global','<div class="alert alert-danger" role="alert" align="center">Du måste välja kurs och universitet!</div>');
}else{
$courses = Posts::where('course_category','LIKE','%'.$course.'%')->get();
return View::make('search')
->with('course_category',$courses)
->with('courses',$courses);
}
}
}
My View:
#extends('layout.main')
#section('content')
{{Form::open(array('method' => 'POST', 'route' =>array('post-search')))}}
<div class="form-group">
{{Form::label('course_category','Språk')}}
{{Form::select('course_category',array(
'' =>'-Choose--',
'php' => 'PHP',
'javascript' =>'Javascript',
'java' =>'Java',
'C#' =>'C#',
'html' =>'HTML',
'css' =>'CSS',
'.net' =>'.NET',
'jquery' =>'jQuery',
'ajax' =>'Ajax'
))}}
</div>
{{Form::submit('Sök',array('class'=>'btn btn-info'))}}
{{Form::token()}}
{{Form::close()}}
#if($courses->count())
#foreach($courses as $c)
<p>{{$c->title}}</p>
#endforeach
#endif
#stop
This is the error that my View search is throwing:
ErrorException (E_UNKNOWN)
Undefined variable: courses (View: /Applications/MAMP/htdocs/LaraBoost/app/views/search.blade.php)
How is it possible that the $courses variable in the view is undefined when i pass it to the View from the Controller?
What did i miss?
Looks like, you have problem in your controller code, the logic doesn't seem right but to overcome the view problem you may try something like this:
#if(isset($courses) && $courses->count())
//...
#endif
Since $courses is undefined then it's not being sent. If you try this instead
#if(isset($courses) && $courses->count())
//...
#else
{{'No Courses'}}
#endif
You'll get the idea and it'll let you understand what you are doing.
I have built a simple application laravel 4. I have scaffolding setup for adding posts which seems to be working fine. I have setup Stapler and image uploading package. When I setup to use single image uploads its pretty good and it works a charm. I recently looked at the docs here
It states that you can do multiple uploads so I went about doing it as explained in the docs. Here are my coded pages:
Post.php model:
<?php
class Post extends Eloquent {
use Codesleeve\Stapler\Stapler;
protected $guarded = array();
// A user has many profile pictures.
public function galleryImages(){
return $this->hasMany('GalleryImage');
}
public static $rules = array(
'title' => 'required',
'body' => 'required'
);
public function __construct(array $attributes = array()) {
$this->hasAttachedFile('picture', [
'styles' => [
'thumbnail' => '100x100',
'large' => '300x300'
],
// 'url' => '/system/:attachment/:id_partition/:style/:filename',
'default_url' => '/:attachment/:style/missing.jpg'
]);
parent::__construct($attributes);
}
}
PostsController.php
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Post::$rules);
if ($validation->passes())
{
$this->post->create($input);
return Redirect::route('posts.index');
}
$post = Post::create(['picture' => Input::file('picture')]);
foreach(Input::file('photos') as $photo)
{
$galleryImage = new GalleryImage();
$galleryImage->photo = $photo;
$user->galleryImages()->save($galleryImage);
}
return Redirect::route('posts.create')
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
This has save functions and other functions inside it too.
GalleryImage.php gallery image model to use in the post controller
<?php
class GalleryImage extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function __construct(array $attributes = array()) {
$this->hasAttachedFile('photo', [
'styles' => [
'thumbnail' => '300x300#'
]
]);
parent::__construct($attributes);
}
// A gallery image belongs to a post.
public function post(){
return $this->belongsTo('Post');
}
}
My create.blade.php template to post the post itself
#extends('layouts.scaffold')
#section('main')
<h1>Create Post</h1>
{{ Form::open(array('route' => 'posts.store', 'files' => true)) }}
<ul>
<li>
{{ Form::label('title', 'Title:') }}
{{ Form::text('title') }}
</li>
<li>
{{ Form::label('body', 'Body:') }}
{{ Form::textarea('body') }}
</li>
<li>
{{ Form::file('picture') }}
</li>
<li>
{{ Form::file( 'photo[]', ['multiple' => true] ) }}
</li>
<li>
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
</ul>
{{ Form::close() }}
#if ($errors->any())
<ul>
{{ implode('', $errors->all('<li class="error">:message</li>')) }}
</ul>
#endif
#stop
When I post the form with a single images attached its fine and saves to the db and it works a treat but when I save it with multiple image uploads I get this error:
ErrorException
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
The full stack trace is here in my gist of the files
Can anyone point out to me why this error happens. From my research its creating a multidimensional array that needs flattening I think but I am unsure if this is true.
I have been banging my head against a brick wall with this for ages.
Problem is when your submitting multiple images it becomes an array of pictures instead of a single string. So its trying to save an array to the database instead of a string which its expecting. If you make it so your photo variable is a json_encoded array of pictures then you should be able to save them.
Hope this helps.