Problem on setting error message if insert fails - laravel

When doing add activity inside store method, after passing validation I am calling a method that returns success or failure.
But on failure, I am not able to handle the code properly.
If I redirect, am not getting the old value.
So How do i return to create method with error message & old value both?
Any way to populate the $errors array?
Am new to Laravel. Thanks in advance
public function store(Request $request, AppMailer $mailer)
{
$validatedData=$request->validate([
.......
........
]);
$tracking_model = new Tracking;
$result = $tracking_model->add($request->all());
if ($result === true) {
return redirect('posts')->with('success', 'Created Successfully');
}
else{
$err_msgs = $result;
//what to do here ???????
// return redirect('posts/create')->with('error', $err_msgs);
}
}

try this
in the controller
return redirect('posts/create')->withInput()->withErrors($err_msgs);
and in view .blade
#if ($errors->any())
#foreach ($errors as $error)
...
#endforeach
#else
No tags
#endif

Related

Laravel API - Display all districts when state field is empty

Below given is my code to display the specific districts of an inputted state. But in this code itself, i want to display all districts in the db if the state field is empty. How to modify my code to get such an output. So, my desired API works such that it returns all the districts when the api is called. And only if the state field is inputted, it shows the particular districts specific to it. Help me with ur suggestions.
public function state_lookup(Request $request)
{
$validator = Validator::make
($request->all(),
[
'state' => 'string',
]
);
if ($validator->fails()) {
return response()->json(
[$validator->errors()],
422
);
}
if(empty($request->state)){
$dist=PersonalDetails::get(['district']);
return response()->json($dist);
}
$data = PersonalDetails::where('state',$request->state)->get(['district']);
// dd($data);
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
else{
return response()->json(['message'=>'Invalid State']);
}
}
in failure case,I am getting json result as below
{
"message": "success",
"data": []
}
it shows "success" instead of "invalid state"
You can use when
$data = PersonalDetails::when(!empty($request->state),function ($query)use($request){
$query->where('state',$request->state);
})->get(['district']);
or
$data = PersonalDetails::where(function ($query)use($request){
if(isset($request)&&!empty($request)){
$query->where('state',$request->state);
}
})->get(['district']);
To avoid 0 key in response change like below
if(count($data)){
return response()->json(['message'=>'success','data'=>$data]);
}
Try with this,
//In your controller
$request->validate([
'state' => 'string'
]);
// $request->validate it self return error messages you have to display
// for an example (write below code in your blade file)
#error('state')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
// write below code in your controller file
$details = PersonalDetails::select('district');
$details->where(function($query) use($request) {
if (isset($request->state) && $request->state != '') {
$query->where('state', $request->state);
}
// do what you want to filter in your query like above
});
$data = $details->get();

How To Display Laravel Breeze Status Message

I'm using Laravel Breeze for authentication, and I'm facing a problem:
When user request a password reset link, I like to show him/her a success message, if we send email successfully. PasswordResetLinkController returns this:
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
When it goes back, it goes, for example, to home route. HomeController returns home.blade.php. When I try to display $status, which should be passed by PasswordResetLinkController, I got undefiened variable error. How can I get that message?
EDIT
PasswordResetLinkController.php
// This is the original store function came with Breeze.
// I did touch neither code nor the comments.
public function store(Request $request)
{
$request->validate([
'email' => 'required|email',
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
HomeController.php
public function index()
{
$baseData = $this->baseData();
$asset = $this->pickAssetRandom();
$publishings = $this->paginate($this->getPublishings, 12);
return view('pages.home', compact('publishings', 'baseData', 'asset'));
}
The $status is being set in the PasswordResetLinkController.
Specifically:
back()->with('status', __($status))
So, as you can see, it is returning the previous page and passing in status.
However, if $status == Password::RESET_LINK_SENT is false, then $status is not set, but the $errors['email'] is. You can see this on the ternary condition in your code.
Try:
dd($status == Password::REST_LINK_SENT);
before the return statement on the controller, if you get false then there will be no $status, and you will get the undefiened variable error.
You can account for this in your view:
#if ($status)
{{ $status }} // A link was sent
#endif
// no link sent and here are the errors.
#if ($errors->any())
#foreach ($errors->all() as $error)
{{ $error }}
#endforeach
#endif
Laravel docs on this: https://laravel.com/docs/8.x/passwords#resetting-the-password
Treat that status as a session and it will work
#if (session('status'))
<span class="alert alert-success">{{ session('status') ?? ''}} </span>
#endif

Method Illuminate\Database\Eloquent\Collection::links does not exist

I created a model relationship between User and Message. I want to implement a list of messages for the authenticated user but I get the following error.
Method Illuminate\Database\Eloquent\Collection::links does not exist
Controller
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $user->message);
}
Message provider
class message extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
User provider
public function message ()
{
return $this->hasMany('App\Message');
}
index.blade.php
#extends('layouts.app')
#section('content')
<h1>messages</h1>
#if(count($messages)>0)
#foreach ($messages as $message)
<div class="well">
<h3>{{$message->user}}</h3>
<small>Written on {{$message->created_at}} </small>
</div>
#endforeach
{{$messages->links()}}
#else
<p> no post found </p>
#endif
#endsection
Error
"Method Illuminate\Database\Eloquent\Collection::links does not exist.(View: C:\xampp\htdocs\basicwebsite\resources\views\message\index.blade.php)"
Check your view blade, that method (links()) only could be used when your data model is implementing paginate() method.
If you dont use paginate(), remove this part:
{{$messages->links() }}
If you are trying to paginate your data when it gets to the view then you need to add the paginate in your controller before passing the data to the view. Example
return $users = Users::select('id','name')->paginate(10);
with that paginate method in your controller, you can call the links method to paginate your object in view as shown below
{{$users->links()}}
hope it helps you
There are 2 ways to resolve this issue:
Either use paginate function while searching data from database:
$users = DB::table('users')->where('id',$user_id)->paginate(1);
Remove links() function from index.blade.php
{{ $messages->links() }}
Remove {{ $messages->links() }} to in your index.blade.php because {{ $messages->links() }} is supported only when you use paginate
You can do something like this in your controller file.
public function index()
{
$messages = Message::all()->paginate(5);
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $messages, $user->message);
}

Trying to get property 'post_titile' of non-object

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>
It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>
May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

Call to a member function isEmpty() on a non-object?

I make my view in the controller via:
$data = Lib::index();
$view = View::make('index')
->with('data', $data)
->render();
return $view;
I can check if data is empty in the controller via:
$data->isEmpty();
But when I try the same thing in the view I get the error:
Call to a member function isEmpty() on a non-object
Why?
Here's the code for Lib::index():
$page = isset($_GET['page']) ? ($_GET['page']) : 1;
Paginator::setCurrentPage($page);
try {
$data = Asset::with(array('sizes'=> function($query){
$query->select('width', 'height', 'asset_id');
}))->where('active', 1)->orderBy('updated_at', 'DESC')->paginate(Config::get('p.results_per_page'), array('id', 'alt'));
}
catch (QueryException $e) {
App::abort(404);
}
return $data;
isEmpty() is a Collection method. For some weird reasons, in views, it sometimes refer to an empty Collection as null. The safest check, in my opinion would be to do a counts check, like so:
if (count($data)) {...}
This works well both in Controllers and Views.
consider you are getting some information as collection;
$UserInfo = User::where('phone', $phone_number)->first();
use this code to for error check
if(empty($UserInfo)){
return redirect()->back()->withErrors('we don't have a user with this phone number ');
}
and add below code into your blade
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
best regards
Try
> var_dump($data);
in the view.
See what it shows up. This might help further investigate the error.
Then In accordance go ahead with
> foreach($data as $moredata){
> $moredata->isEmpty(); }
Should work.

Resources