I have a beginner problem please:
I know how to pass data to the view as below:
$data['documents'] = $this->documents_model->get_documents();
$data['main_content'] = 'document_view';
$this->load->view('layout', $data);
I also know how to pass errors to the view as below:
$this->load->view('upload_view', array('error' => ''));
But how can I pass both data and error to the view? I tried placing the error into $data-key as below, but that gives me the word 'array' in the view which I don't want.
$data['error'] = array('error' => '');
I also tried sending $error and $data in the load->view (as 2 params seperated by comma) which gives me syntax error. And now I ran out of my limited ideas so I thought I ask here.
Thank you very much for advice.
Try like this:
$data['error'] = "Your message here";
Now, in the view just echo the message like this:
<?=(isset($error))?$error:''?>
Related
I am working on a laravel project in which I am trying to show image using url but getting error. I have tried a lot and search everything but I don't understand why I am getting this error. I am using the below function
public function displayImage($filename){
$path = storage_path("app/taskImage/".$filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = \Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
}
And the route is
Route::get('taskImg/{filename?}', [
'uses' => 'FormController#displayImage',
]);
And the URL which I am tring is like
http://localhost/project_name/public/taskImg/test.jpg
when I have print something I am getting the that but Not getting the Image. It is showing a blank screen with error message The image cannot be displayed because it contains errors
you can do it like this way
$storagePath = storage_path("app/taskImage/".$filename);
return Image::make($storagePath)->response();
I've spent a LOT of hours searching for a solution for this, I found it at last! just add ob_end_clean before returning the response, like the following:
ob_end_clean();
return response()->file($path,['Content-type' => 'image/jpeg']);
I can't explain because I don't know what was going on, any one could explain this?
I use stard auth from Laravel but I want to send var to auth's view. Actually I want to send title of website and keywords. In other controllers I can do that
return view('my.view')->with('title', 'My funny title');
How I can do that in Login, Register...
perhaps you should do something like this.
in your controller( you will find this controller in AuthenticatesUsers Traits located in Illuminate\Foundation\Auth folder.
$title= "my page title";
return view('my.view', compact('title'));
and in view, just use {{ $title }} where ever you cant to call that text. this should work.
Add this on baseController/Controller __construct() function
by this you will share the variable to every blade file.
$siteTitle = 'SiteTitle';
View::share($siteTitle);
Maybe try with this syntax as in documentation
return view('my.view', ['title' => 'My funny title']);
or
$data = [
'title' => 'My funny title',
...
];
return view('my.view', $data);
I remember having the similar issues while ago, though i cant remember how exactly i worked it out.
In Laravel's unit test, I can test a JSON API like that:
$this->post('/user', ['name' => 'Sally'])
->seeJson([
'created' => true,
]);
But what if I want to use the response. How can I get the JSON response (as an array) using $this->post()?
Proper way to get the content is:
$content = $this->get('/v1/users/1')->decodeResponseJson();
Currently, in 5.3 this is working...
$content = $this->get('/v1/users/1')->response->getContent();
However, it does break the chain since response returns the response and not the test runner. So, you should make your chainable assertions before fetching the response, like so...
$content = $this->get('/v1/users/1')->seeStatusCode(200)->response->getContent();
As at Laravel 8, this worked for me.
I was returning an automatically generated field (balance) after the POST request has created the entity.
The response was in the structure {"attributes":{"balance":12345}}
$response = $this->postJson('api/v1/authors', [
'firstName' => 'John',
'lastName' => 'Doe',
])->assertStatus(201);
$balance = $response->decodeResponseJson()['attributes']['balance'];
decodeResponseJson will pick the response and transform it to an array for manipulation.
Using getContent() returns json and you will have to use json_decode on the returned data to turn it into an array.
I like to use the json method when working with json, instead of ->get()
$data = $this->json('GET', $url)->seeStatusCode(200)->decodeResponseJson();
I hit a similar problem and could not get $this->getResponse()->getContent() working with the built in $this->get() method. I tried several variations with no success.
Instead I had to change the call to return the full http response and get the content out of that.
// Original (not working)
$content = $this->get('/v1/users/1')->getContent();
// New (working)
$content = $this->call('GET', '/v1/users/1')->getContent();
Simple way:
$this->getJson('api/threads')->content()
Just want to share, I have used the same in $this->json() like:
$response = $this->json('POST', '/order', $data)->response->getContent();
But I added one more line to use json response and decode otherwise decodeResponseJson() was not working for me.
$json = json_decode($response);
Found a better way:
$response = $this->json('POST', '/order', $data);
$responseData = $response->getOriginalContent(); // saves the response as an array
$responseData['value'] // you can now access the array values
This method returns the response json as an array.
You can just call:
$data = $response->json();
$response = $this->json('POST', '/products', $data);
$data = $response->getData();
Let me tell you my situation. I have made a simple library/module which I can popupulate in my controller. This way I can use one view file and have different results just by changing some of the $form fields(like text inputs, selects, etc). The example is below:
$form = new FormHelper('Webshop bewerken','shop/update',$errors);
$form->addHiddenInput('id',$id);
$form->addTextInput('name','Naam',$item->name);
$form->addTextInput('export','Uitvoer',$item->output_location);
$form->addTextInput('method','Methode',$item->method);
$form->addSidebar();
$form->generateForm();
//show the page
$this->layout->content = View::make('item')->with('form',$form);
The problem exist not within the form. This works fine until i need to validate. However the $errors is undefined so i cannot render the errors.
I have noticed that this variable is only available in the view and not in the controller.
This is fine if you have just a few blade.php files but not in my case(many many screens with generic information).
How can I access the $errors variable (output from the laravel validator) in a controller and not view?
Below is a validator code example i use:
//run the validator
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()->withInput()->withErrors($validator);
} else {
//do something else(not relevant)
}
In your controller you may use:
$validator = Validator::make(Input::all(), $rules);
$errors = $validator->errors();
This will give you the same errors that you get in the view. To access a particular error you may use:
$error = $validator->errors('someFormFieldName')->first();
I'm using the validation rules in Laravel 4, which are very powerful. However, I wonder how one can distinguish between the different validations error that may occur. For example if I use the following rules:
$rules = array(
'email' => 'required|email|confirmed',
'email_confirmation' => 'required|email',
);
How can I tell what validation rule/rules that triggered the error for a certain field? Is there some way I can tell that the error was due to a missing email value, email wasn't a valid email address and/or the email couldn't be confirmed?
I quite new to laravel as I began working with it a week ago so I hope someone may shed some light on this.
The validation messages returned by the validation instance should hold the key to knowing what went wrong.
You can access the messages given by the validator object by using:
$messages = $validator->messages(); // Where $validator is your validator instance.
$messages = $messages->all()
That should give you an instance of a MessageBag object, that you can run through with a foreach loop:
foreach ($messages as $message) {
print $message;
}
And inside there, you should find your answer, i.e. there will be a message saying something like: "Email confirmation must match the 'email' field".
You can get error messages for a given attribute:
$errors = $validation->errors->get('email');
and then loop through the errors
foreach ($errors as $error) {
print $error;
}
or get all the error messages
$errors = $validation->errors->all();
then loop through the error messages
foreach ($errors as $error) {
print $error;
}
You can see more information about laravel validation here